【问题标题】:Redirecting www to non www on server with wildcard subdomains使用通配符子域将 www 重定向到服务器上的非 www
【发布时间】:2011-04-10 04:42:04
【问题描述】:

我有一个 Rails+Apache+Passenger 设置,我的应用程序提供通配符子域。我需要所有 www 网址重定向到它们的非 www 等价物。

  • www.example.net 应该重定向到 example.net
  • www.subdomain.example.net 应该重定向到 subdomain.example.net

我当前的虚拟主机配置如下

<VirtualHost *:80>

  ServerName  example.net
  ServerAlias *.example.net

  DocumentRoot /home/public_html/example.net/current/public

  RailsEnv staging

</VirtualHost>

我在不同位置尝试了各种重写规则,但没有一个生效。我已经检查以确保 apache 重写模块已启用并且 RewriteEngine 已打开。不知道我错过了什么。非常感谢所有帮助!

【问题讨论】:

    标签: ruby-on-rails apache redirect passenger wildcard-subdomain


    【解决方案1】:

    我在我的应用程序中解决了这个问题,因为无论如何我都有基于域的逻辑。将此代码放在您的 ApplicationController 中

    class ApplicationController < ActionController::Base
        before_filter :check_host
    
        def check_host
            if request.host.split('.')[0] == 'www'
                redirect_to "http://" + request.host.gsub('www.','')
            end
        end
    end
    

    如果您的某些主机名包含“www”,则可能会有特殊情况。出于任何其他您必须编写代码的原因。

    【讨论】:

    • 我想避免在代码级别执行此操作,因为理想情况下它应该在代码被命中之前发生。
    【解决方案2】:

    您可以在 .htaccess 文件中使用 moderewrite。

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www\.example\.net [NC]
    RewriteRule ^(.*)$ http://example.net/$1 [R=301,NC]
    
    RewriteCond %{HTTP_HOST} ^www\.subdomain\.example\.net [NC]
    RewriteRule ^(.*)$ http://subdomain.example.net/$1 [R=301,NC]
    

    这应该可以,但我没有测试它。
    或者这个

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

    【讨论】:

    • 我尝试将这些条件放在我的 rails 应用程序公共文件夹下的 .htaccess 文件中,但它不起作用。另外,我正在提供通配符子域,那么重写条件和规则应该如何查找呢?
    • @jcubic 有没有办法反过来。我总是想拥有www。对于访问该网站的任何域。
    • 还有一件事,在我的主机上,对于每个域,我都有该域的“A”DNS 记录,www 与子域相同。
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多