.htaccess - get current url and pass part of it as variable

天大地大妈咪最大 提交于 2021-01-01 06:36:21

问题


I need to write optimized .htaccess rules. I had written like that and they are working

RewriteEngine on
RewriteRule ^city1-name-in-url/$ products.php?city=city1-name-in-url
RewriteRule ^city2-name-in-url/$ products.php?city=city2-name-in-url
RewriteRule ^city3-name-in-url/$ products.php?city=city3-name-in-url
RewriteRule ^city4-name-in-url/$ products.php?city=city4-name-in-url

And url for these rules are http://www.domain.com/global/city1-name-in-url/

I have to write these rules for 800 cities which is making website slow. I want to know if there is anyway to get the part url and use it in RewriteRule

Example like

If url : http://www.domain.com/global/any-city-name/

RewriteRule ^any-city-name/$ products.php?city=any-city-name

This is possible ? To get the part of url after global and then use it in rewrite rule

Thanks


回答1:


You can use this rule in /global/.htaccess:

RewriteEngine On

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w-]+)/?$ products.php?city=$1 [L,QSA]

[\w-]+ matches 1 or more of [a-zA-Z0-9_-] characters.



来源:https://stackoverflow.com/questions/36283417/htaccess-get-current-url-and-pass-part-of-it-as-variable

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