MontyHall
MontyHall

Reputation: 524

How to prevent trailing slash on 404ing URLs that end with an extension in .htaccess?

URLs with extensions resolve properly if they exist on the server, but if they don't exist, they 404, which is to be expected, but then the 404'd URLs get a trailing slash. Is there any way to prevent the trailing slashes on those 404'ing URLs?

Below is the .htaccess file in the root directory of my Wordpress install.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://example.com%{REQUEST_URI} [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

# BEGIN MainWP
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-content/plugins/mainwp-child/(.*)$ /wp-content/plugins/THIS_PLUGIN_DOES_NOT_EXIST [QSA,L]
</IfModule>
# END MainWP
Options -MultiViews

Upvotes: 1

Views: 445

Answers (1)

MrWhite
MrWhite

Reputation: 45914

To prevent a trailing slash from being added to URLs that end in an extension then it looks like you can just add another condition (ie. RewriteCond directive) to exclude such files from having a slash appended and redirected.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]

So, to prevent URLs that end in .html or .php from being processed:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !.+\.(html|php)$
RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]

Note that you will need to clear any intermediary caches, as the previous 301s will have been cached by the browser.

To handle any extension (of say between 2 and 4 chars), then you could perhaps do something like:

RewriteCond %{REQUEST_URI} !.+\.[a-z]{2,4}$

Upvotes: 1

Related Questions