简体   繁体   中英

URL Rewriting with multiple rules: wrong $_GET variable

I'm very new to URL rewriting. What I'd like to achieve is to have 2 main rules:

  1. Hide all .php extensions
  2. Rewrite 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!

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]

如果只想重写数值,则应限制第二条规则:

RewriteRule   ^p/(\d+)$   p.php?id=$1   [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM