如何通过htaccess更改浏览器中的URL?

时间:2014-10-10 19:13:19

标签: php regex apache .htaccess mod-rewrite

我想通过htaccess更改我的网址 http://example.com/offer?search=something http://example.com/offer/something

以下htaccess适用于http://example.com/offer/something,但如果我输入http://example.com/offer?search=something,则网址不会更改为http://example.com/offer/something

RewriteEngine On
RewriteRule ^offer/([^/]*)$ /offer?search=$1 [L]

我应该使用" rewritecond"?在这种情况下,正确的htaccess是什么?

我尝试在Laravel框架中制作它。我只有一个htaccess,这是内容,目前:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{QUERY_STRING} ^search=([-a-zA-Z0-9]+)
RewriteRule ^offer$ /offer/%1? [R=301,L]
RewriteRule ^offer/([^/]*)$ /offer?search=$1 [L]
</IfModule>

2 个答案:

答案 0 :(得分:3)

更新:完整.htaccess:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On
RewriteBase /

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# redirect URL with GET parameter to pretty URL
RewriteCond %{THE_REQUEST} \s/+offer\?search=([^\s&]+) [NC]
RewriteRule ^ /offer/%1? [R=301,L]

# rewrite from pretty URL to actual handle
RewriteRule ^(offer/[^/]+)/?$ index.php/$1 [L,QSA]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

</IfModule>

它如何阻止循环: THE_REQUEST变量表示Apache从您的浏览器收到的原始请求,在执行其他重写规则后不会被覆盖,unline {{ 1}}在其他规则之后被覆盖。此变量的示例值为%{REQUEST_URI}

答案 1 :(得分:1)

您还需要在网址中包含一个包含查询字符串的重定向。我没有对此进行测试,但第一条规则应该捕获第一个URL并将其重定向到新格式。第二个规则应该捕获新格式并将正确的值传递给搜索参数。

RewriteEngine On
RewriteCond %{QUERY_STRING} ^search=([-a-zA-Z0-9]+)
RewriteRule ^offer$ /offer/%1? [R=301,L]
RewriteRule ^offer/([^/]*)$ /offer?search=$1 [L]