将多条路由路由至默认页面

时间:2018-09-20 作者:Mike Cole

我有多条路线需要指向索引。php来处理React应用程序中的路由。以下是路线列表:

/login
/logout
/profile
/sign-up
/coming-soon
/forgot-password
/content/:content_id
我所能找到的信息似乎只是重定向和重写,但并不是很多关于路由的信息。有人能给我指出正确的方向吗?

我已尝试将以下内容添加到我的函数中。php文件:

function custom_rewrite_basic() {
   add_rewrite_rule(\'^login/?\', \'index.php\', \'top\');
}
add_action(\'init\', \'custom_rewrite_basic\');
然后转到设置=>永久链接并单击保存更改,但导航到http://myurl.com/login 不带我去索引。php。

1 个回复
SO网友:filipecsweb

在这里,请注意代码及其注释:

function my_custom_rewrite_for_react() {
    // Add to your resource \'index.php\' a param and its value. Here I chose as an example \'custom_template\' and the value \'1\'.
    add_rewrite_rule( \'^login/?\', \'index.php?custom_template=1\', \'top\' );
    add_rewrite_rule( \'^/logout/?\', \'index.php?custom_template=1\', \'top\' );

    // WordPress does not know your custom param, so tell it.
    add_rewrite_tag( \'%custom_template%\', \'([^&]+)\' );

    /**
     * Filters the path of the current template before including it.
     *
     * @link    https://developer.wordpress.org/reference/hooks/template_include/
     */
    add_filter( \'template_include\',
        /**
         * @param   string  The path of the template to include.
         */
        function ( $template ) {
            global $wp_query;

            // In this example \'chosen_template\' equals to \'1\'.
            if ( ! empty( $wp_query->query_vars[\'custom_template\'] ) ) {
                // $path will be equal to something like /var/www/my-app/public/wp-content/my-theme/index.php
                $path = STYLESHEETPATH . \'/index.php\';

                if ( file_exists( $path ) ) {
                    $template = $path;
                }
            }

            return $template;
        }
    );
}

add_action( \'init\', \'my_custom_rewrite_for_react\' );

// Delete this function once everything is working fine!
// Using the function bellow is the same as visiting the Permalinks page in admin.
flush_rewrite_rules();
顺便说一句,您的代码实际上可以工作,但它会将状态为301的您重定向到http://yoursite.com/index.php将您重定向到http://yoursite.com,因为wordpress就是这样工作的。

要真正注意到重定向,可以打开终端(Unix)并键入curl -v http://myurl.com/logincurl -v http://myurl.com/index.php.

结束

相关推荐

Debugging WP routing

对于一些帖子,我看到404页,即使存在帖子,在WP中使用永久链接决定需要呈现什么对象的位置在哪里?谢谢