简体   繁体   English

PHP-在Apache中使用mod_rewrite

[英]PHP - Using mod_rewrite in Apache

I have the following URL: 我有以下网址:

http://example.com/pages/page.php?company_name=Name http://example.com/pages/page.php?company_name=名称

What I want to achieve is to have a URL like this: 我想要实现的是拥有这样的URL:

http://example.com/pages/Name http://example.com/pages/名称

I have tried different rules but they don't work: 我尝试了不同的规则,但它们不起作用:

RewriteRule ^pages/([A-Za-z0-9-]+)/?$ /pages/page.php?company_name=$1 [NC] or

RewriteRule ^pages/([^/]*)\.php$ /pages/page.php?company_name=$1 [L]

It doesn't work. 没用 It gives me a "not found" page. 它给了我一个“找不到”页面。 How can I properly use mod_rewrite? 如何正确使用mod_rewrite?

Try this out: 试试看:

RewriteRule ^pages/([0-9a-zA-Z\-_]*)(/|)$ /pages/page.php?company_name=$1 [QSA,L]

This will care or not care if the url has a trailing slash: 不管URL是否带有斜杠,这都可以或不可以:

http://example.com/pages/Name
http://example.com/pages/Name/

And will also include any extra agrs (QSA) if the page calls for it: 如果页面需要,还将包括任何额外的agr(QSA):

http://example.com/pages/Name/?more=stuff

That should work, if your apache has mod_rewrite and the php exists where you have shown. 如果您的apache具有mod_rewrite并且php存在于您显示的位置,那应该可以。

UPDATE 更新

If you have a different url that needs a different php, for example 'bluepages': 如果您有一个不同的URL需要一个不同的php,例如'bluepages':

http://example.com/bluepages/Name

Then this would work for that: 然后这将适用于:

RewriteRule ^bluepages/([0-9a-zA-Z\-_]*)(/|)$ /bluepages/somescript.php?some_var=$1 [QSA,L]

If you have multiple like this you wish to control, you can make multiple RewriteRules in your htaccess for each one. 如果您希望控制多个这样的控件,则可以在htaccess中为每个控件创建多个RewriteRules。 However if you just want to wildcard it, then this would do a blind catchall (and cause lots of error reports in your apache logs): 但是,如果您只想通配它,那么这将导致盲目性(并在您的Apache日志中导致大量错误报告):

RewriteRule ^([0-9a-zA-Z]*)/([0-9a-zA-Z\-_]*)(/|)$ /$1/page.php?some_var=$2 [QSA,L]

You will either need to be specific, or just change everything. 您要么需要具体说明,要么只需更改所有内容。 There are so many ways one can go with it, and it really depends on your intent. 一个人可以使用很多方法,这实际上取决于您的意图。

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

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