How can I rewrite query parameters to path parameters in Apache?

爱⌒轻易说出口 提交于 2021-01-27 18:37:43

问题


I currently have a website that I am trying to optimize in terms of SEO.

I've got the site working with URLs such as:

domain.com/?app=about

In my app, $_GET[app] is set to 'about', as expected.

Now, I want to make it so that a URL like domain.com/about is treated as if it were domain.com/?app=about.

How can I do this in an Apache .htaccess file?


回答1:


These are known as RewriteRules, and they are fairly straightforward:

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]




回答2:


Use this in your .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. Doing R=301 will forward the browser to the rewritten page, which is useful for debugging.




回答3:


Creating a general .htaccess getting the path requested can be done with the following line:

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. Use the PHP function urldecode() to get the original format.

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.



来源:https://stackoverflow.com/questions/1114950/how-can-i-rewrite-query-parameters-to-path-parameters-in-apache

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