apache虚拟主机配置

apache虚拟主机配置

你好,我想确保我的网站只能通过 https 访问,并且只能通过 www 子域访问,我目前使用以下 apache 虚拟主机配置:

<VirtualHost *:80>
ServerAdmin [email protected]
ServerName example.com
ServerAlias www.example.com

# Redirect http requests to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]

RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=permanent,L]

#..
</VirtualHost>

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName example.com
ServerAlias www.example.com

# Redirect http requests to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]

RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]

RewriteCond %{SERVER_NAME} !=www.example.com
RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,NC,L]

<Directory /home/{apacheuser}/www>
  SSLRequireSSL
  Order allow,deny
  Allow from all
  LimitRequestBody 512000
</Directory>

#..
</VirtualHost>

恐怕我对正则表达式的了解相当有限,我想知道这是否是实现这一目标的最佳方法?

谢谢

答案1

  1. 只需更换

    # Redirect http requests to https
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]
    
    RewriteCond %{HTTP_HOST} !=www.example.com
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R=permanent,L]
    

经过

    # Redirect http requests to https
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !=www.example.com
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]

就像所有 http 流量都将被重定向到 https,但http://example.com要求

  1. 然后从你的 https 配置中删除那行:

    # Redirect http requests to https
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R,L]
    
    RewriteCond %{HTTP_HOST} !=www.example.com
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,L]
    

所以只要保持

    RewriteCond %{SERVER_NAME} !=www.example.com
    RewriteRule .* https://www.example.com%{REQUEST_URI} [R=301,NC,L]

哪个重定向https://example.comhttps://www.example.com

答案2

%{SERVER_ADDR}也可以重写 IP

编辑:

抱歉,您不能在表达式的右侧使用变量。

尝试这样的事情:

RewriteCond %{SERVER_NAME},%{SERVER_ADDR} ^(.*),\1

或者如果你不采用动态方式

RewriteCond %{SERVER_NAME} !192.168.1.1

相关内容