Search code examples
.htaccessurl-rewriting

URL Rewriting using htaccess giving error 404


Hi I am new to URL Rewriting. Using htaccess I want to rewrite:

URL: https://example.com/services/state.php?state=CO&city=Arvada

to

https://example.com/services/CO/Arvada/

I tried following but it is giving 404 error:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^state=([A-Za-z]+)&city=([A-Za-z]+)$
RewriteRule ^services/state\.php$ /services/%1/%2? [R=301,L]

state.php file is located in root/services directory while htaccess file is located in root directory.


Solution

  • You have to write the rule for the URL: https://example.com/services/CO/Arvada/ that's why you get 404 error

    RewriteEngine On
    RewriteBase /
    
    # Rule for services/STATE/CITY/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^services/([^/]*)/([^/]*)/?$ /services/state.php?state=$1&city=$2 [END]
    
    # Redirect state.php?state=STATE&city=CITY to services/STATE/CITY
    RewriteCond %{QUERY_STRING} ^state=([A-Za-z]+)&city=([A-Za-z]+)$
    RewriteRule ^services/state\.php$ services/%1/%2 [QSD, R=301,END]
    

    Here is better using END instead of L because with END Apache will not process any other rules, if you use L using these rules it will fall in a redirect loop

    In the rule:

    RewriteRule ^services/state\.php$ services/%1/%2 [QSD, R=301,END] the QSD means to not append query string