Rajat
Rajat

Reputation: 34118

Mod rewrite for query string

Mod Rewrite noob so pardon my ignorance but all I am trying to do is a simple query string removal

from: http://yourwebsite.com/x?section=y

to: http://yourwebsite.com/x/y

I am adding my mod rewrite rules in my .htaccess like this:

ErrorDocument 404 /404

Options +MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

RewriteCond %{QUERY_STRING} ^section=(.*)$ [NC]
RewriteRule ^(.*)$ /$1/%1? [R=301,L,NE]

The problem is that on visiting:

http://yourwebsite.com/x?section=y

My rule writes it back as:

http://yourwebsite.com/x.php/y

That .php in the pretty url is pretty darn ugly and I am struggling to get rid of it.

What is wrong in my mod rewrite rule?

Upvotes: 0

Views: 173

Answers (1)

arkascha
arkascha

Reputation: 42895

Most likely you are looking for something like this:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d  
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)\/(.+)$ /$1.php?section=$2 [L]

RewriteCond %{QUERY_STRING} ^section=(.*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ /$1/%1 [R=301,L,NE]

It makes two rewrites:

  1. a request x/y is internally rewritten to x.php?section=y
  2. a request to x?section=y is redirected to x/y

Note that one is an internal rewrite, whilst the other redirects the browser to show a less 'ugly' url.

One hint: in case you can use the logging feature of apaches rewriting module (RewriteLog and RewriteLogLevel) this will offer you a wealth of detailed information on what is actually going on inside the rewrite process.

Upvotes: 1

Related Questions