4

Using .htaccess from my previous question, I edited it to add a rewrite rule for rewriting /contact/ to /contact.php and /xyz/contact/ to /contact.php?lang=xyz. While the second one works, the first still looks for the actual directory which doesn't exist, returning 404 code. Both redirects to the nice URL variant work just like expected. Here is my .htaccess settings for that:

# No directory listing, no multi views, follow symlinks
Options -Indexes -MultiViews +FollowSymLinks

# Redirects and rewrites allowed
RewriteEngine on

# ...

# Redirect direct requests for "contact.php?lang=xyz" to "/xyz/contact/"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^lang=([a-z]{2,3})$
RewriteRule ^contact\.php$ /%1/contact/? [R=301,L]

# Redirect direct request for "contact.php" to "/contact/"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^contact\.php$ /contact/? [R=301,L]

# Internally rewrite "/xyz/contact/" to "/contact.php?lang=xyz"
RewriteRule ^([a-z]{2,3})/contact/?$ /contact.php?lang=$1 [L]

# ...

# Internally rewrite "/contact/" to "/contact.php"
RewriteRule ^/contact/?$ /contact.php [L]

1 Answer 1

7
# Internally rewrite "/contact/" to "/contact.php"
RewriteRule ^/contact/?$ /contact.php [L]

In per-directory .htaccess files you need to remove the slash prefix on the RewriteRule pattern (as you have done on the earlier directives). So this should be written as:

RewriteRule ^contact/?$ /contact.php [L]

This matches requests for /contact and /contact/.

The slash prefix is not used on the RewriteRule pattern because in a .htaccess context, the directory-prefix (that notably ends with a slash) is first removed from the URL-path that the RewriteRule pattern matches against. (The directory-prefix being the filesystem path of where the .htaccess file is located.)

2
  • I'm really dumb :D Thank you, overlooked the mistake :D
    – Polda18
    Apr 2, 2018 at 15:46
  • It's a common mistake - you're not dumb! ;) By contrast, if you were using these directives directly in the server config (ie. in a server or virtualhost context) then you would need the slash prefix, because when used in a server context, the RewriteRule pattern matches against the full root-relative URL-path.
    – MrWhite
    Apr 2, 2018 at 15:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .