Puneet
Puneet

Reputation: 33

htaccess redirect with GET request

Following is my htaccess:

Options -Multiviews -Indexes
RewriteEngine on
RewriteBase /

## don't touch /Forum URIs
RewriteRule ^Forum/ - [L,NC]

## hide .php extension snippet

# To externally redirect /dir/foo.php?id=123 to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?seo=([^&\s]+) [NC] 
RewriteRule ^ %1/%2? [R,L]

# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/([^/]+)/?$ $1.php?seo=$2 [L,QSA] 

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\s [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*?)/?$ $1.php [L]

Above codes are working fine except for following two scenario:

  1. .php extension is not getting removed for pages under 'Forum' directory. Their is no GET request in these pages. If I remove the condition for Forum above then gives 404 error Forum/.php not found.

  2. Also, .php extension is not getting removed for pages where GET request variable is other than 'seo'.

  3. URL with 'seo' as GET variable are converting into SEO friendly but GET request with other variables like 'id' or 'rg=&vp=&da=' are not working. I have added additional rules (as for seo) for the same but still no impact.

Kindly advise.

Upvotes: 3

Views: 2114

Answers (1)

anubhava
anubhava

Reputation: 786291

Have your .htaccess like this:

Options -Multiviews -Indexes
RewriteEngine on
RewriteBase /

## hide .php extension snippet

# To externally redirect /dir/foo.php?id=123 to /dir/foo
RewriteCond %{THE_REQUEST} \s(.+?)\.php\?seo=([^&\s]+)(?:&(\S+))? [NC] 
RewriteRule ^ %1/%2?%3 [R,L]

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s(.+?)\.php(\S*) [NC]
RewriteRule ^ %1%2 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/([^/]+)/?$ $1.php?seo=$2 [L,QSA] 

Upvotes: 1

Related Questions