I set up my website so that all pages load without the .html extension, using the following code in the .htaccess file:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]
It works beautifully on the main site. The problem is that I have a few subdomains on the same site, and this change has been disastrous for those pages, with files and folders loading in ways they shouldn't.
Is it possible to do either of the following?:
a) Set up the above code to only target specific pages? This would be preferable, I think, if it's possible to do. Only 9 pages in the main site need load without the .html extension. So for example, maybe one of those "RewriteCond"s could be:
RewriteCond services.html -f
(And I have no idea if that's correct code - it's just an example of one page that needs to load without the .html extension.)
b) Alternately, could the above .htaccess code be rewritten to ADD the .html extension back in? Maybe I could add that to the subdomains' individual .htaccess files, and hopefully it would "overwrite" the main .htaccess code.
Hope someone who is more fluent at .htaccess than I am has some ideas! Thanks in advance.
Jen
EDIT: Solution found! Thanks to some new terms given in the comments (especially mod_rewrite), I did more searching and found that the following code works to enable non-.html links:
RewriteRule ^page$ /page.html [L,E=END:1]
RewriteCond %{ENV:END} !1
RewriteRule ^page.html$ /page [R=301,L]
The above code enables links to work without the .html extension. The only catch is that links that have the .html extension will still load WITH the extension (it's not removed automatically) but that's a minor issue to me. I just wanted to be able to use nicer-looking links.
Credit to my commenter Stephen, who actually solved this question years ago at: Remove extension from URL using a rewrite without resulting in a redirect loop
.htaccess
files for security, performance and simplicity reasons, and 2) for very simple needs, and specially because you are saying you need the feature for only 9 pages, look at simpler stuff likemod_alias
and itsRedirect
directives. I also suggest not matchingTHE_REQUEST
as this is far too much for the simple needs you have...mod_autoindex
or equivalent jumps in. Anyway, make sure to have your.htaccess
file in the specific subdirectory of the virtual host you want it to apply, and not for all virtual hosts. And I recommend reworking your last 2 lines of configuration.