How can I change the URL in the browser by htacces

2019-08-29 10:49发布

I want to change my url by htaccess from http://example.com/offer?search=something to http://example.com/offer/something

The following htaccess works from http://example.com/offer/something but if I typing the http://example.com/offer?search=something then the url is not changing to http://example.com/offer/something.

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

Should I use "rewritecond"? What is the correct htaccess in this case?

I try make it in Laravel framwork. I have only one htaccess and this is the content, currently:

<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条回答
Rolldiameter
2楼-- · 2019-08-29 11:18

UPDATE: Full .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>

How it prevents looping: THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of other rewrite rules, unline %{REQUEST_URI} which gets overwritten after other rules. Example value of this variable is GET /index.php?id=123 HTTP/1.1

查看更多
叛逆
3楼-- · 2019-08-29 11:30

You also need to include a redirect from the url that contain a query string. I haven't tested this, but the first rule should catch the first URL and redirect it to the new format. The second rule should catch the new format and pass the correct values to the search parameter.

RewriteEngine On
RewriteCond %{QUERY_STRING} ^search=([-a-zA-Z0-9]+)
RewriteRule ^offer$ /offer/%1? [R=301,L]
RewriteRule ^offer/([^/]*)$ /offer?search=$1 [L]
查看更多
登录 后发表回答