Apache Force WWW & SSL 以及支持其他子域名

Apache Force WWW & SSL 以及支持其他子域名

我已经搜索了好几个小时,虽然已经非常接近成功了,但是仍然没有完全成功。

我目前将其作为我的虚拟主机文件。

ServerName example.com
DocumentRoot /mnt/WWW
ServerAdmin [email protected]
RemoteIPHeader X-Forwarded-For

# Needed before any rewriting
RewriteEngine On

### Built using the .htaccess 301 Redirect Generator from Web Site Advantage
### https://websiteadvantage.com.au/HtAccess-301-Redirect-Generator
### Place after 'RewriteEngine On' and before any CMS specific rewrite rules

# Redirect HTTP with www to HTTPS with www
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Redirect HTTP without www to HTTPS with www
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Redirect HTTPS without www to HTTPS with www
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## 301 Redirects

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

<VirtualHost *:443>
    DocumentRoot "/mnt/WWW/www.example.com"
    ServerName www.example.com
    ServerAlias www.example.com

    <Directory />
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted
    </Directory>

    SSLEngine on
    SSLCertificateFile /root/ssl/example.com.crt
    SSLCertificateKeyFile /root/ssl/private.key
    SSLCACertificateFile /root/ssl/intermediateCA.crt
</VirtualHost>

<VirtualHost *:443>
    # NAS
    ServerName nas.example.com
    ServerAlias nas.example.com

    ProxyPass / http://10.0.28.1:5000/
    ProxyPassReverse / http://10.0.28.1:5000/

    SSLEngine on
    SSLProxyEngine on
    SSLCertificateFile /root/ssl/example.com.crt
    SSLCertificateKeyFile /root/ssl/private.key
    SSLCACertificateFile /root/ssl/intermediateCA.crt
</VirtualHost>

现在我要尝试执行此操作。我有根文件夹 /mnt/WWW。

我希望所有 HTTP 请求都自动切换到 https。然后我希望所有非 www 子域都保留为子域,但强制 example.com 始终为 www.example.com

目前,上述工作方式如下:

http://example.com      -> https://www.example.com     = Correct
http://www.example.com  -> https://www.example.com     = Correct
http://sub.example.com  -> https://www.sub.example.com = Wrong - Should be https://sub.example.com
https://example.com     -> https://example.com         = Wrong - Should be https://www.example.com
https://www.example.com -> https://www.example.com     = Correct
https://sub.example.com -> https://sub.example.com     = Correct

我可以让其中的大多数在某个时候工作,但是还不能让它们全部在一个配置下同时工作。

此外,我正在尝试通过将常用设置设为默认值来简化代码。还有其他方法可以最大限度地减少所有反向代理等共有的重复行吗?

答案1

我将重写内容更改为以下内容:

#Force WWW Subdomain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[0-9a-zA-Z-]+\.[a-zA-Z]{2,}$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}:443$1 [R=301,L]

#Force SSL
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}:443$1 [R,L]

现在一切正常。

相关内容