Nanoripper Nanoripper - 1 year ago 83
Apache Configuration Question

Converting querystring to directory view

I am trying to use htaccess mod-rewrite to change some links I use. I am pretty good at other stuff(PHP & MySQL) but when it comes to this htaccess stuff my mind just leaves me.

Here is what I want:



and also if a page variable is also set like this:



But I also want .php extension to be hidden in whole website, not only for item.php. Like this:


Also if anyone visits the old boring links(item.php or item.php?id=1) they should be forwarded to their changed versions (/item or /item/1).

I did this to hide the php extension:

RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.+)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,QSA,L]

And also did this to forward item.php with querystrings:

RewriteRule ^item/([0-9]+)/?$ /item.php?id=$1

They seem to work separately but not together. I just can't figure out how to make it work for all these different stuff together.

I also want to be able to use

$_GET['id'] and $_GET['page']

as normal in item.php

Answer Source

You will need few more rules to make all this work together:

Options -MultiViews
RewriteEngine On

# external redirect /item.php?id=1&page=view to /item/view/1
RewriteCond %{THE_REQUEST} \s/+item\.php\?id=([^\s&]+)&page=([^\s&]+) [NC]
RewriteRule ^ /item/%2/%1? [R=302,L,NE]

# external redirect /item.php?id=1 to /item/1
RewriteCond %{THE_REQUEST} \s/+item\.php\?id=([^\s&]+) [NC]
RewriteRule ^ /item/%1? [R=302,L,NE]

# external redirect /user.php to /user
RewriteCond %{THE_REQUEST} \s/+(.+)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,L,NE]

# internal rewrite /item/view/1 to /item.php?id=1&page=view
RewriteRule ^item/([\w-]+)/(\d+)/?$ item.php?id=$2&page=$1 [L,QSA,NC]

# internal rewrite /item/1 to /item.php?id=1
RewriteRule ^item/(\d+)/?$ item.php?id=$1 [L,QSA,NC]

# internal rewrite /user to /user.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)$ $1.php [L]


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download