开发者

How to write in htaccess file to force trailing slash and www at the same time

开发者 https://www.devze.com 2023-03-29 16:13 出处:网络
Im trying to implement 2 rules 1) Forced www. I have got it working by doi开发者_如何学Gong RewriteCond %{HTTP_HOST} ^domain.com

Im trying to implement 2 rules

1) Forced www.

I have got it working by doi开发者_如何学Gong

RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

2) Add trailing forward slash on all urls

I got this far by doing this

RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com/$1/ [R=301,L]

and then I ran into a problem,

type url

1) www.domain.com --rewrites to--> http://www.domain.com/  ---Desired Result

2) domain.com --rewrites to--> http://www.domain.com//  ---Undesired Result

3) domain.com/location1 --rewrites to--> http://www.domain.com/location1/  ---Desired Result

4) www.domain.com/location1 --rewrites to--> http://www.domain.com/location1  ---Undesired Result

How can I write it so that i get these 2 rules working?


this rule will redirect all visits without the www:

RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com$1 [R=301]

See that I removed the flag to make it the last rule.

and the second one to put the trailing slash:

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

It won't redirect when the URL already ends in a slash. You'll get 2 redirects when someone visits a page without the www and without the slash. If you just want to do this due to search engines, it is fine. If your own site often point to a URL like this, you'll need another regexp.

If SEO is your motive, also take a look to canonical URLs


try putting the add slash part before the www part - should work fine.


I've never used this directive, but two thoughts that may be helpful come to mind:

  1. Your original patterns do nothing to exclude URLs that already end with a slash. I think you need a pattern more like

    ^domain.com.*[^/]

Otherwise URLs that end with a slash pass, and so another slash is added.

  1. Why are you doing this, anyway?

Why change the host name to add the "www"? If the request is making it to your server, then with or without the www, it made it, so why do you care? If the request is not making it to your server, then your rules will never be applied anyway, as of course . I was thinking that maybe your example is oversimplified, maybe in real life you're redirecting to a different server. But in that case, why would you care what the original host name was at all? Just fill in the host name you need.

Why add the slash? Apache servers automatically add the slash if the name turns out to be a directory anyway. You can't have a file and a directory with the same name, so at most this would just change the error message on not-founds.

0

精彩评论

暂无评论...
验证码 换一张
取 消