apache 如何始终使用 mod_rewrite 从 url 中删除 WWW?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2361499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 18:51:22  来源:igfitidea点击:

How to always remove WWW from a url with mod_rewrite?

apachemod-rewrite

提问by Yeti

I'm using the following to try and remove WWW from the url:

我正在使用以下内容尝试从 url 中删除 WWW:

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

But for some reason it doesn't work. Any suggestions?

但由于某种原因它不起作用。有什么建议?

回答by Gumbo

Here's a more generalized solution:

这是一个更通用的解决方案:

RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

回答by Kyle Rozendo

Try:

尝试:

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

And without mod_rewrite:

并且没有mod_rewrite

<VirtualHost 10.0.0.1:80>
        ServerName www.example.com
        Redirect permanent / http://example.com/
</VirtualHost>

Virtual hosts can be used by completing the steps in the following URL: Setting Up A Virtual Host in Apache.

可以通过完成以下 URL 中的步骤来使用虚拟主机:在 Apache 中设置虚拟主机

回答by Fredrik Bostr?m

As a minor tweak of Kyle's answer, I'd put a / in the RewriteRule match condition, like

作为凯尔回答的一个小调整,我会在 RewriteRule 匹配条件中放一个 / ,比如

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

Otherwise, you get a double slash as a result.

否则,您会得到双斜线。

http://www.example.com/smth -> http://example.com//smth

回答by Konrad H?ffner

I would always use 307 (temporary redirect) first because if you get it wrong some browsers cache it permanently. I ended up installing Google Chrome just because I couldn't get my Firefox to forget a bad redirect even when I deleted the whole cache.

我总是首先使用 307(临时重定向),因为如果你弄错了一些浏览器会永久缓存它。我最终安装了 Google Chrome,因为即使我删除了整个缓存,我也无法让我的 Firefox 忘记错误的重定向。

回答by seaBass

Here is a solution if you don't want a hard coded domain name. Don't forget to start the rewrite engine or this won't work!

如果您不想要硬编码域名,这里有一个解决方案。不要忘记启动重写引擎,否则这将不起作用!

 # Start rewrite engine
 <IfModule mod_rewrite.c>
   Options +FollowSymlinks
   RewriteEngine On
 </IfModule>

 # Rewrite "www.example.com -> example.com"
 <IfModule mod_rewrite.c>
   RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
   RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
 </IfModule>