Search code examples
.htaccesshttp-redirectmod-rewriteurl-rewritingfriendly-url

.htaccess ModRewrite: Url was not found


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!


Solution

  • 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.