How can I solve this problem in mod_rewrite ,htaccess?

Tag: .htaccess , mod-rewrite Author: susan_0923 Date: 2011-08-22

I have problem in removing php extension using .htaccess. Here is the rule :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php?$2 [QSA,L]

This link sak.ps/overview works well for www.sak.ps/overview.php, but sak.ps/overview/1 for sak.ps/overview.php?flag=1 gives internal server error !

But in both cases the URL appear in URL tab with php extension.

Other Answer1

You don't need that ?$2 on the end of your rule there, the QSA flag will automatically append the query string, by its very definition.

If I'm not mistaken, the error is because there's no second capture group in your rule regex.

Other Answer2

1. In your rule $2 will always be empty as you have no corresponding capture group.

2. Your rule will only work for URLs where .php extension is added to the end of the requested URL. For your second URL example you will need to have separate rule.

RewriteEngine on

# 1) add .php file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]

# 2) more complex case of adding .php extension
# will work with URLs like
# /overview/something/here => /overview/something.php?flag=here
# /overview/1 => /overview.php?flag=1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(.+)/([^/]+)$ $1.php?flag=$2 [QSA,L]

# 3) Another type of URL
# will work with URLs like
# /overview/something/here => /overview.php?flag=something/here
# /overview/1 => /overview.php?flag=1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)/(.+)$ $1.php?flag=$2 [QSA,L]

I have provided rules for 2 approaches:

  • Rule #2 will handle /overview/something/here => /overview/something.php?flag=here (the last segment will be treated as parameter while all previous segments will be treated as file name);

  • Rule #3 will handle /overview/something/here => /overview.php?flag=something/here (the first segment will be treated as file name while all other segments will be treated as parameter);

The /overview/1 => /overview.php?flag=1 rewrite can be handled by both of them (#2 or #3).