的.htaccess力和QU​​OT; WWW"在一切,但子域和删除尾随斜杠 [英] .htaccess force "www." on everything but subdomains and remove trailing slashes

查看:95
本文介绍了的.htaccess力和QU​​OT; WWW"在一切,但子域和删除尾随斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止有:

#Force www.
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

#Remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} (.*)$
RewriteRule ^(.+)/$ http://www.domain.com/$1 [R=301,L]

不过,这打乱了做以下重定向所有子:

However, this messes up all subdomains doing the following redirect:

sub.domain.com -> www.sub.domain.com

和也,它依赖于写在删除斜线位域。

And also, its dependant on the domain written on the remove trailing slash bit.

所以......两个问题。

So... two questions.

我如何重写规则上的删除尾随斜杠位排除写入域名就可以了?

How do I rewrite the rule on the "remove trailing slash" bit to exclude writing the domain on it?

我如何做一个的RewriteCond排除子域,但没有明确写下来,就力WWW。位?

How do I make a rewritecond to exclude subdomains, without explicitly writing them down, on the "force www." bit?

预期的效果的例子 -

Examples of desired results -

sub.domain.com/something/ -> sub.domain.com/something
domain.com/something/ -> www.domain.com/something
www.domain.com/ -> www.domain.com
sub.domain.com -> sub.domain.com

谢谢!

推荐答案

更​​改WWW检查实际的域:

Change the www to check for the actual domain:

#Force www.
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

或者,如果你正在主持一帮域,您可以在TLD之前检查的名称:

Or, if you're hosting a bunch of domains, you can check for a name before the TLD:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^([^.]+)\.([a-z]{2,4})$ [NC]
RewriteRule ^ http://www.%1.%2%{REQUEST_URI} [L,R=301]

对于斜线,你必须要小心,请求不是一个目录进行。因为如果是这样,你有 DirectorySlash 打开(默认情况下它是),那么你就会导致重定向循环。

As for the trailing slash, you have to be careful that the request isn't made for a directory. Because if it is, and you have DirectorySlash turned on (by default it is on), then you'll cause a redirect loop.

要排除的子域,我们假设第一条规则重定向浏览器,以确保它开始与WWW,并且由于子域没有被重定向到以WWW,我们可以只检查是否存在:

To exclude subdomains, we assume that the first rule redirected the browser to ensure that it started with "www", and since subdomains aren't being redirected to start with "www", we can just check for that:

#Remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.+)/$ /$1 [R=301,L]

这篇关于的.htaccess力和QU​​OT; WWW"在一切,但子域和删除尾随斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆