Rewrite query string parameter into URL Apache

时间秒杀一切 提交于 2020-01-15 18:50:35

问题


URL coming into Apache:

localhost:8888/game?level=0

URL that should be coming out of apache:

localhost:8888/level0/game

Could someone kindly help me to create this rewrite ?

Tried to solve it with following:

RewriteEngine On
RewriteRule ^game\/+(.*?)\?+level=+([0-9]+) /level$2/$1 [L,QSA]

With no luck since it does not match.

Thanks, Peter


回答1:


To be able to capture values from the query string, you need a RewriteCond %{QUERY_STRING} directive, so that captured group will be available as %n placeholders in the following RewriteRule:

RewriteCond %{QUERY_STRING} ^level=(.*)$
RewriteRule ^game /level%1/game [L]

If you type /game?level=0 in the browser, apache will open /level0/game; no need to append the query string to the rewritten url (QSA flag)




回答2:


You can use this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On
RewriteBase /

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /(game)\?(level)=(\d+) [NC]
RewriteRule ^ %2%3/%1? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^(level)(\d+)/([^/.]+)/?$ $3?$1=$2 [L,QSA,NC]


来源:https://stackoverflow.com/questions/28721423/rewrite-query-string-parameter-into-url-apache

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