Rewrite Url (URL Routing) in .htaccess

2019-08-29 06:29发布

问题:

My directories are like:

http://www.mydomain.com/macbook-computer 
http://www.mydomain.com/sony-computer
http://www.mydomain.com/lenovo-computer

I want to make that, if a user type computers/macbook-computer like:

http://www.mydomain.com/computers/macbook-computer  

I want to display page which is : http://www.mydomain.com/macbook-computer.

My restrictions are:

1. User must type /computers                                (segment 1)
2. String coming from computers/ must end with "computer".  (segment 2)   

How can I make this achieve in my .htaccess file?

回答1:

You may try this:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/computers/([^-]+)-computer/? [NC]
RewriteRule .*  %1-computer?  [R=301,L]

Redirects permanently

http://www.mydomain.com/computers/anyname-computer with or without trailing slash.

To:

http://www.mydomain.com/anyname-computer

Strings computers and computer are assumed to be fixed, while anything is assumed to be variable.

The incoming URL structure has to be kept for the rule-set to work: First folder /computers followed by /anyname-computer.

For silent mapping, remove R=301 from [R=301,L]



回答2:

You need a rewrite rule in your .htaccess file, and a little regular expression magic. Something like this should do the trick

RewriteRule ^computers/macbook-computer$ http://www.mydomain.com/macbook-computer 

Here's a nice online tool for checking rewrite rules

http://htaccess.madewithlove.be/