user1040259 February 2016

htaccess to resolve a trailing slash to .html page

Is it possible to resolve a page to it's .html equivalent if someone removes the extension and adds a trailing slash?

http://www.example.com/page.html

http://www.example.com/page/ <-- adding trailing slash resolve to page.html.

However, I want the trailing slash to be optional and not something that I add in htaccess.

RewriteEngine on

# render .php as .html
RewriteRule ^(.*)\.html$ $1.php [nc]

# don't need extension on the end
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.html [NC,L]

# .php to .html
RewriteCond %{THE_REQUEST} \ /(.+)\.php
RewriteRule ^ /%1.html [L,R=301]

Answers


starkeen February 2016

To make the trailing slash optional for html requests, you can use :

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)/?$ $1.html [NC,L]


anubhava February 2016

Have it like this:

RewriteEngine On

# .php to .html
RewriteCond %{THE_REQUEST} \ /(.+)\.php[?\s] [NC]
RewriteRule ^ /%1.html [L,R=301]

# don't need extension on the end
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

RewriteRule ^(.+)\.html/?$ $1.php [L,NC]

Make sure to clear your browser cache before testing this change.

Post Status

Asked in February 2016
Viewed 3,237 times
Voted 4
Answered 2 times

Search




Leave an answer