Clean URL and php file extension removal

Viewed 34

I want to achieve two things with .htaccess:

  1. Only show the value in the URL parameter "slug" making the URL clean
  2. For all other php pages on my site which doesn't have the URL parameter "slug" simply remove the file extension ".php".

I have the following .htaccess code which takes care of point 1 above:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ somepage.php?slug=$1 
RewriteRule ^([a-zA-Z0-9_-]+)/$ somepage.php?slug=$1

The question is; how do I incorporate point 2 above in the same code without breaking what is already working in point one?

I have tried simply including the following code below the above but this gives me a 404 error when I go to example.com/somepage:

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^([^\.]+)$ $1.php [NC,L]
1 Answers

You need to prioritise your extensionless .php URLs, so this rule needs to go before your existing rule that rewrites the "slug".

You also need to check that the corresponding .php file exists before rewriting the request. The rule you are currently proposing blindly rewrites the request when the request does not map to a file, so this would naturally catch requests that should otherwise be rewritten to the "slug".

Try it like this instead (in the root .htaccess file):

RewriteEngine On

# Handle extensionless ".php" files
RewriteCond %{DOCUMENT_ROOT}/$1.php -f 
RewriteRule ^([^.]+)$ $1.php [L]

# Rewrite to "slug"
RewriteRule ^([\w-]+)/?$ somepage.php?slug=$1 [L]

I've combined your two rules that rewrite to "slug" into one, since the only difference is the trailing slash - just make it optional in the regex. The \w shorthand character class in the same as [a-zA-Z0-9_]. HOWEVER, consider canonicalising the trailing slash instead (ie. redirect to one or the other). Since by allowing an optional trailing slash (two different URLs) to serve the same content you are potentially creating a duplicate content issue.

I have tried simply including the following code below the above but this gives me a 404 error when I go to example.com/somepage

The request would have been rewritten to somepage.php?slug=somepage, so I assume it must have been somepage.php that generated the 404 response, rather than Apache?

Related