简体   繁体   English

使用.htaccess重写重定向URL的规则

[英]Rewrite rules for redirect URLs using .htaccess

I am using .htaccess to redirect URLs on my website to avoid having links like for example page1.php. 我正在使用.htaccess重定向我网站上的URL,以避免出现诸如page1.php之类的链接。

I have a subfolder engine/index.php on the root domain that i intend to use to process the redirected URL. 我打算在根域上使用子文件夹engine/index.php来处理重定向的URL。

eg i want the link localhost/user to rewrite to localhost/engine/index.php?view=user NOTE:The links being used ie /user is not a file or folder existing on the domain 例如,我希望链接localhost/user重写为localhost/engine/index.php?view=user注意:正在使用的链接,即/ user不是域中存在的文件或文件夹

Use this: 用这个:

RewriteEngine On

RewriteRule ^([a-z]+)$ engine/index.php?view=$1 [NC,L,QSA]

Put this in your .htaccess file directly in your www/ directory. 将其直接放在www/目录中的.htaccess文件中。
([az]+) will match a group of letters (also capitals since the NC flag is used), but if something else than a letter is behind localhost/ the url won't be rewritten. ([az]+)将匹配一组字母(由于使用了NC标志,所以也要使用大写字母),但是如果在localhost/没有字母,则该URL将不会被重写。 If there are only letters behind localhost , the url will rewritten to engine/index.php?view=$1 如果localhost后面只有字母,则该URL将被重写为engine/index.php?view=$1

The L flag indicates that this is the last RewriteRule , and the QSA flag appends the old querystring to the new one. L标志指示这是最后一个RewriteRule ,而QSA标志将旧的查询字符串附加到新的查询字符串。 For example: localhost/user?var=val will redirect to localhost/engine/index.php?view=user&var=val . 例如: localhost/user?var=val将重定向到localhost/engine/index.php?view=user&var=val

But , if the user goes to localhost/user?view=somethingelse , it will be rewritten to localhost/engine/index.php?view=user&view=somethingelse which means that if you do $_GET['view'] in engine.php , it will return "somethingelse" . 但是 ,如果用户转到localhost/user?view=somethingelse ,它将被重写为localhost/engine/index.php?view=user&view=somethingelse ,这意味着如果您在engine.php执行$_GET['view']它将返回“ somethingelse” To get the first view parameter from the querystring ( user ), use this regex in PHP: 要从querystring( user )获取第一个view参数,请在PHP中使用此正则表达式:

$view = preg_replace('/view=([^&]+).*/', '$1', $_SERVER['QUERY_STRING']); //now, $view contains 'user'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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