How do I clean URL
http://localhost/mysitedirectory/contacts.php
to look like both:
http://localhost/mysitedirectory/contacts
http://localhost/mysitedirectory/contacts/
I want this because a user may add the ending trailing slash or leave it so I want .htaccess to configure such that it works both ways.
I noticed when I add the /
at the end of the contacts
it says "OBJECT NOT FOUND"...Error 404
How do I make it work even if I add the slash or not?
this is what I tried:
RewriteEngine On
Options -Indexes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^contacts$ contacts.php [L,QSA,NC]
RewriteRule ^home$ index.php [L,QSA,NC]
CodePudding user response:
CBroe answered in a comment section:
^contacts/?$
- slash at the end, made optional by the following quantifier question mark.
CodePudding user response:
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^contacts$ contacts.php [L,QSA,NC] RewriteRule ^home$ index.php [L,QSA,NC]
The two RewriteCond
directives (filesystem checks) are entirely superfluous and should be removed. (As are the QSA
flags on the RewriteRule
directives.)
However, instead of allowing both /contacts
and /contacts/
(strictly speaking two different URLs) resolve to the same content (which would necessitate the need for a rel="canonical"
tag) you should externally redirect from one to the other (canonical) URL.
By the look of it, the URL without the trailing slash is canonical, so remove the trailing slash with an external redirect. The only thing to be careful of is that you should not remove the trailing slash from physical directories (which would ordinarily cause a redirect loop).
For example:
Options -Indexes -MultiViews
RewriteEngine On
# Canonical redirect to remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (. )/$ /$1 [R=301,L]
# Internal rewrites
RewriteRule ^contacts$ contacts.php [L,NC]
RewriteRule ^home$ index.php [L,NC]
The NC
flag on the RewriteRule
directives makes contacts
, CONTACTS
and CoNtAcTs
all resolve to the same content. (So the rel="canonical"
tag is still required to resolve this ambiguity.)