URL Rewrite GET parameters

拟墨画扇 提交于 2019-12-28 02:48:06

问题


I want my url to look like the following

www.website.com/home&foo=bar&hello=world

I only want the first get parameter to change

However the actual "behind the scenes" url is this

www.website.com/index.php?page=home&foo=bar&hello=world

All tutorials I find change all of the parameters.

Any help much appreciated!


回答1:


Add this to your .htaccess in your web root / directory

RewriteEngine on
RewriteBase /

RewriteRule ^home$ index.php?page=home&%{QUERY_STRING} [NC,L]

If you want this to work for all pages i.e. /any-page gets served as index.php?page=any-page then use

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d # not a dir
RewriteCond %{REQUEST_FILENAME} !-f # not a file
RewriteRule ^(.*)$ index.php?page=$1&%{QUERY_STRING} [NC,L]


How do these rules work?

A RewriteRule has the following syntax

RewriteRule [Pattern] [Substitution] [Flags]

The Pattern can use a regular expression and is matched against the part of the URL after the hostname and port (with the .htaccess placed in the root dir), but before any query string.

First Rule

The pattern ^home$ makes the first rule match the incoming URL www.website.com/home. The %{QUERY_STRING} simply captures and appends anything after /home? to the internally substituted URL index.php?page=home.

The flag NC simply makes the rule non case-sensitive, so that it matches /Home or /HOME as well. And L simply marks it as last i.e. rewriting should stop here in case there are any other rules defined below.

Second Rule

This one's just more generic i.e. if all of your site pages follow this URL pattern then instead of writing several rules, one for each page, we could just use this generic one.

The .* in the pattern ^(.*)$ matches /any-page-name and the parentheses help capture the any-page-name part as a $1 variable used in the substitution URL as index.php?page=$1. The & in page=home& and page=$1& is simply the separator used between multiple query string field-value pairs.

Finally, the %{QUERY_STRING} and the [NC,L] flags work the same as in rule one.



来源:https://stackoverflow.com/questions/18162686/url-rewrite-get-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!