Add Trailing Slash for certain page types

Add Trailing Slash for certain page types - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, mod-rewrite, , , .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


I would like to add a trailing slash for certain static page types like .html, .asp and .pdf.



I tried the following code in .htaccess but it is adding a trailing slash to all types of links.



# Force trailing slash
RewriteEngine On
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_METHOD GET
RewriteCond %REQUEST_URI !(.*)/$
RewriteRule ^(.*)$ https://%HTTP_HOST/$1/ [L,R=301]


My site bought from a previous owner has many .html, .asp and .pdf pages which are now showing server errors in Google webmaster tools. Now I am using WordPress default permalink structure and with the redirection plugin, those static pages are not redirecting unless I force a trailing slash on them.


Solution :

Redirecting to append a trailing slash so you can use the "redirection plugin" to redirect these requests again doesn't make a whole lot of sense. (This would seem to suggest that these "static pages" still exist? Although the directives you posted suggest otherwise?)



Anyway, to answer your question (assuming these pages don't exist)...



Your current RewriteRule targets every URL (ie. (.*)), so it naturally appends a trailing slash to all URLs. You need to target just the URLs that end .html, .asp and .pdf. And if you do this you don't need the condition that checks that a trailing slash is not already present on the URL-path.



I don't think you really need to check the REQUEST_METHOD either?



So, this could be written:



RewriteCond %REQUEST_FILENAME !-f
RewriteRule (.+.(?:html|asp|pdf))$ /$1/ [L,R=301]

Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect