重定向所有www和http ==>>带有Load Balancer的AWS Elastic Beanstalk上的非www https

时间:2014-05-01 16:21:26

标签: apache .htaccess mod-rewrite amazon-web-services amazon-ec2

我目前已将此功能定位为将所有http流量重定向到https

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

以上工作正常。

现在我尝试添加重写条件,强制所有https://www流量到https而没有www

请注意,这是在Elastic Load Balancer后面运行Apache的AWS Elastic Beanstalk

=============================

编辑:

工作代码:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

4 个答案:

答案 0 :(得分:3)

请尝试使用此规则:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

答案 1 :(得分:1)

实际上RewriteCond %{HTTP:X-Forwarded-Proto} ^http$ [OR]会更好,因为!=https无法通过ELB运行状况检查。所以完整的答案是:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$ [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

答案 2 :(得分:1)

要同时考虑到ELB健康检查,请使用:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

答案 3 :(得分:0)

仅适用于正在寻找使用ElasticBeanstalks配置文件的完整复制和粘贴解决方案的人。

  1. .ebextensions/中创建文件,将其命名为01-https.config
  2. 添加以下内容:
files:
  "/etc/httpd/conf.d/http-redirect.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      RewriteEngine On
      RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC]
      RewriteCond %{HTTP:X-Forwarded-Proto} !https
      RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
      RewriteRule (.*) https://example.com%{REQUEST_URI}

这考虑了ELB健康检查,并且适用于以下示例:

将被重定向到https://example.com