Bram Vanroy
Bram Vanroy

Reputation: 28505

Rewrite URL's parameters and remove query string

I am trying to do a 301 re-direct and a re-write my URL parameters in one go. I have been following some answers around here, but can't get it to work. Here is what I tried. Comments indicate what I hope it does, not what it actually does.

RewriteEngine on

# Redirect from "/country.php?country=FR&recipe=Croissant" to "/FR/Croissant"
RewriteCond %{THE_REQUEST} ^country\.php/?country=([A-Z]{2})&recipe=(.+) [NC]
RewriteRule ^/%1/$2 [NE,L,R=301]
# Redirect from "/country.php?country=FR" to "/FR"
RewriteCond %{THE_REQUEST} ^country\.php/?country=([A-Z]{2}) [NC]
RewriteRule ^/%1 [NE,L,R=301]

# Internally map "/FR/Croissant" to "/country.php?country=FR&recipe=Croissant"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/([A-Z]{2})/(.+)/?$ country\.php/?country=$1&recipe=$2 [L]
# Internally map "/FR" to "/country.php?country=FR"
RewriteRule ^/([A-Z]{2})/?$ country\.php/?country=$1 [L]

But this does not work. Nothing happens when I try either of the examples:

/country.php?country=FR&recipe=Croissant stays /country.php?country=FR&recipe=Croissant and /FR/Croissant returns a 404.

I am running this on a subdirectory of a domain (localhost/food/, with localhost/food/index.php and localhost/food/country.php), but the htaccess file is placed in that directory localhost/food/.

What am I doing wrong?

Upvotes: 1

Views: 100

Answers (1)

anubhava
anubhava

Reputation: 785581

You need to fix regex pattern and some syntax issues:

RewriteEngine on
RewriteBase /food/

# Redirect from "/country.php?country=FR&recipe=Croissant" to "/FR/Croissant"
RewriteCond %{THE_REQUEST} /country\.php\?country=([A-Z]{2})&recipe=([^&\s]*) [NC]
RewriteRule ^ %1/%2? [NE,L,R=301]

# Redirect from "/country.php?country=FR" to "/FR"
RewriteCond %{THE_REQUEST} /country\.php\?country=([A-Z]{2}) [NC]
RewriteRule ^ %1? [NE,L,R=301]

# ignore rules below for files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# Internally map "/FR/Croissant" to "/country.php?country=FR&recipe=Croissant"
RewriteRule ^([A-Z]{2})/(.+?)/?$ country.php?country=$1&recipe=$2 [L,QSA]

# Internally map "/FR" to "/country.php?country=FR"
RewriteRule ^([A-Z]{2})/?$ country.php?country=$1 [L,QSA]

To fix issue with styles, images etc you need to use absolute path in your css, js, images files rather than a relative one. Which means you have to make sure path of these files start either with http:// or a slash /.

Or else, you can add this just below <head> section of your page's HTML:

<base href="/food/" />

so that every relative URL is resolved from that base URL and not from the current page's URL.

Upvotes: 1

Related Questions