Redirect all urls to the root except /wp-admin and wp-json

13,058

You seem to have destroyed the WordPress front-controller, so any requests for the /wp-admin and /wp-json will not be correctly routed (hence the 404s you are seeing).

You should leave the WP directives as they were, but implement an additional redirect at the start of the file. For example:

# Redirect all requests for non-existent files and those not for wp-admin or wp-json
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/wp-admin
RewriteCond %{REQUEST_URI} !^/wp-json
RewriteRule ^ / [R=301,L]

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Note that, as in your original code, the request is only redirected when requesting a non-existent file, even if that file lies outside of the /wp-admin and /wp-json URL space. (Presumably this is required so that CSS, JS, images and any other static resources still get served correctly.)

Share:
13,058

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    I try to redirect all urls to the root except for the wordpress administration and the wordpress REST API.

    I have these rules in my .htaccess:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/wp-admin.*
    RewriteCond %{REQUEST_URI} !^/wp-json.*
    RewriteRule ^.*$ / [L,R=301]
    </IfModule>
    

    It's work perfectly for all redirections expect for the /wp-json route where I get 404 errors.

    Also, I have these errors types in my apache log file: File does not exist: [...]/dmjob/wp-json, referer: http://dmjob.dev:8888/

    Can you please help me ? Thanks a lot ! :)