.htaccess ModRewrite: Url was not found

Viewed 57

My goal is to redirect http://ipaddress/directory/file.php?id=47 to http://ipaddress/directory/47 with .htaccess. The id parameter will vary and can be any string of numbers like 1, 2, 3, 10, 20, 300, etc. My current .htaccess file is below:

RewriteEngine on
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule (.*) /directory/%1? [R=301,L]

The rewrite does change the url to what I want! But I get an error after being redirected, which states, Not Found - The requested URL was not found on this server. I'm not sure why the redirect works but does not load the previous page which had the id parameter and actual PHP file.

Thank you!

2 Answers

With your shown samples please try following rules. Make sure your htaccess is present in root folder. Make sure to clear your browser cache before testing your URLs.

##Making RewriteEngine ON here.
RewriteEngine on
##Checking condition if THE_REQUEST is in same format which OP has mentioned for URI and mentioning Rule then.
RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\d+)\s [NC]
RewriteRule ^ /directory/%1? [R=301,L]
RewriteRule ^directory/(\d+)/?$ /directory/file.php?id=$1 [NC,L,QSA]

You will need an internal rewrite for

RewriteEngine on

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule ^file\.php$ /directory/%1? [R=301,L,NC]

RewriteRule ^directory/(\d+)/?$ /directory/file.php?id=$1 [L,QSA,NC]

RewriteCond %{ENV:REDIRECT_STATUS} ^$ condition is used to make sure that redirect rule is not executed in the next loop of mod_rewrite after rewriting is done from last rules.

Related