简体   繁体   中英

mod_rewrite and GET parameters

I have a site which uses pages with the following style:

index.php?page=X&id=Y

For example, for a blog it will be

index.php?page=blog&id=65

, for a picture it could be

index.php?page=picture&id=26

I am trying to set up a rewrite rule such that people can use mysite.com/page or mysite.com/page/id but coming up with issues when passing two parameters.

For some reason, it's redirecting me to the right page and then immediately reloading the same page with no parameters, ie it will load index.php?page=blog&id=65 and then immediately reload index.php?page=blog , which is useless.

The code I'm using:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /

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

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

Any suggestions will be appreciated. Thanks.

The best way to attack this problem is to redirect all requests to a router page (usually the index.php file), and have it to include the actual requested file from there. It gives you much much better control over what you redirect where, and allows for more complex rules than RegEx can easily achieve.

As for your specific problem. It could either be a JavaScript that's reloading your window, or you're having some Location: headers somewhere in your PHP code.

Read up on the mod_rewrite documentation and specifically on the [QSA] (query string append) flag. Without this, the rewrite engine will dump existing parameters if you specify new ones in your replacement string. With it, it will append the old ones.

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