I have multiple routes that I need pointed at index.php to handle routing in a React app. Here's a list of routes:


All I can seem to find information for is redirection and rewriting, but not a whole lot about routing. Can somebody point me in the right direction?

I have tried adding the following to my functions.php file:

function custom_rewrite_basic() {
   add_rewrite_rule('^login/?', 'index.php', 'top');
add_action('init', 'custom_rewrite_basic');

and went to Settings => Permalinks and clicked Save changes, but navigating to http://myurl.com/login does not take me to index.php.


1 Answer 1


Here you go, pay attention to the code and its comments:

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.

By the way, your code actually works, but it's redirecting you with status 301 to http://yoursite.com/index.php which redirects you to http://yoursite.com, because that's how wordpress works.

To actually notice the redirecting you could open your terminal (Unix) and type curl -v http://myurl.com/login or curl -v http://myurl.com/index.php.

  • With this I am still getting a 404. I copied and pasted as-is into functions.php.
    – Mike Cole
    Sep 21, 2018 at 16:24
  • Odd. I tested the code myself and it's working fine. Sep 23, 2018 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.