简体   繁体   English

如何在Apache中将查询参数重写为路径参数?

[英]How can I rewrite query parameters to path parameters in Apache?

I currently have a website that I am trying to optimize in terms of SEO. 我目前有一个网站,我试图优化SEO。

I've got the site working with URLs such as: 我的网站使用以下网址:

domain.com/?app=about domain.com/?app=about

In my app, $_GET[app] is set to 'about', as expected. 在我的应用中, $_GET[app]设置为'about',正如预期的那样。

Now, I want to make it so that a URL like domain.com/about is treated as if it were domain.com/?app=about . 现在,我想这样做,以便将domain.com/about这样的网址视为domain.com/?app=about

How can I do this in an Apache .htaccess file? 我怎么能在Apache .htaccess文件中这样做?

These are known as RewriteRule s, and they are fairly straightforward: 这些被称为RewriteRule ,它们相当简单:

RewriteEngine on
RewriteRule ^about$ /index.php?app=about

Here's the documentation 这是文档

As far as making it more generic, how about this: 至于使它更通用,这是怎么回事:

RewriteEngine on
RewriteRule ^([A-Za-z]+)$ /index.php?app=$1

This will make any request to something like /staff or /contact redirect to index.php?app=[staff|contact] 这会对/ staff或/ contact重定向到index.php这样的任何请求?app = [staff | contact]

Use this in your .htaccess 在你的.htaccess中使用它

RewriteEngine on
RewriteBase /your-site # only if neccessary

RewriteRule ^([^/])$ index.php?app=$1 [R,L]

EDIT 编辑

I added the L flag meaning process this as the last rule, and the R flag which by itself does not change the URL .. just rewrites internally. 我添加了L标志意味着将此作为最后一条规则,并且R标志本身不会更改URL ..只是在内部重写。 Doing R=301 will forward the browser to the rewritten page, which is useful for debugging. 执行R = 301会将浏览器转发到重写的页面,这对调试很有用。

Creating a general .htaccess getting the path requested can be done with the following line: 创建获取所请求路径的通用.htaccess可以使用以下行完成:

RewriteRule ^((.+/)+)$ /index.php?path=$1 [L,B]

This will give you the path requested escaped properly so if the requested path is /hello/world you will get hello%2Fworld in the path parameter. 这将为您提供正确请求转义的路径,因此如果请求的路径是/ hello / world,您将在path参数中获得hello%2Fworld Use the PHP function urldecode() to get the original format. 使用PHP函数urldecode()获取原始格式。

Works only if the url ends with '/'. 仅当网址以“/”结尾时才有效。

NOTE If you have other rewrites in the same file you should place this one last as it will match basically anything. 注意如果你在同一个文件中有其他重写,你应该把它放在最后,因为它基本上匹配任何东西。

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

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