Reputation: 131
I'm very new to URL rewriting. What I'd like to achieve is to have 2 main rules:
domain.com/p.php?id=1
to domain.com/p/1
Here's what I have so far:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule ^p/(.+)$ p.php?id=$1 [L]
This seemed to work at first: all .php extensions are hidden, and typing domain.com/p/1 displayed domain.com/p.php?id=1.
However, I've just realized that the PHP GET method on this page picks up a wrong value: whereas I want it to pick up 1
, it actually picks up 1.php/1
. I didn't notice it at first because the database query based on $_GET
actually works, which seems odd to me now that I know the value is wrong.
How could I make the combination of these two rewrite rules work as intended?
Thank you!
Upvotes: 1
Views: 84
Reputation: 786329
Place this code in your DOCUMENT_ROOT/.htaccess
file:
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+p\.php\?id=([0-9]+) [NC]
RewriteRule ^ /p/%1? [R=301,L]
RewriteRule ^p/([0-9]+)/?$ /p.php?id=$1 [L,QSA,NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]
Upvotes: 1
Reputation: 91792
If you just want to rewrite the numerical values, you should restrict your second rule:
RewriteRule ^p/(\d+)$ p.php?id=$1 [L]
Upvotes: 0