Apache Mod_将www重写为非www不工作

nhaq1z21  于 2023-08-07  发布在  Apache
关注(0)|答案(1)|浏览(99)

我试图做一个Mod_Rewrite,并摆脱所有**www.**在网址。我所有的SSL证书都是非www的,我不想为www创建SSL证书。子域。我只想重写和重定向。

<VirtualHost *:80>
 ServerAdmin webmaster@localhost
 DocumentRoot /var/www/html
 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined
 RewriteEngine on
 RewriteCond %{HTTPS} off
 RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}
 RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
 RewriteRule ^ https://%1%{REQUEST_URI} [END,L,R=permanent]
</VirtualHost>
<Directory /var/www>
 Options Indexes FollowSymLinks
 AllowOverride All
 Require all granted
</Directory>

字符串
其次是sudo systemctl restart apache2,但经过测试,www.仍然是持久的。

tag5nh1u

tag5nh1u1#

<VirtualHost *:80>
 ServerAdmin webmaster@localhost
 DocumentRoot /var/www/html
 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined
 RewriteEngine on
 RewriteCond %{HTTPS} off
 RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}
 RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
 RewriteRule ^ https://%1%{REQUEST_URI} [END,L,R=permanent]
</VirtualHost>

字符串
您发布的规则位于<VirtualHost *:80>容器中,因此它仅适用于HTTP(非HTTPS)流量。但是,它将永远不会被处理,因为您在前面的规则中重定向到“同一主机”上的HTTPS。如果您希望优先删除www子域(通过HTTP访问时),则需要颠倒这两个规则。(通常,这只需要在<VirtualHost *:443>(HTTPS)容器中完成。
(但是,如果您希望实现HSTS,那么规则已经按正确的顺序排列。尽管你缺少了第一条规则中的 flags 参数。)
但是,您还缺少来自此vHost容器的ServerNameServerAlias指令,因此不清楚www子域是否会在此处解析(或者哪个域在此处解析)。
举例来说:

ServerName example.com
 ServerAlias www.example.com

 :

 RewriteEngine on
 RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
 RewriteRule ^ https://%1%{REQUEST_URI} [R=permanent,L]
 RewriteCond %{HTTPS} off
 RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


但是,如果您希望将HTTPS流量从www重定向到非www,那么您别无选择,只能确保SSL证书也覆盖www子域(否则请求甚至不会到达您的服务器)。删除www的相关规则需要在<VirtualHost *:443>(HTTPS)容器中重复。

相关问题