大网数据广告活动
服务器运维问答

Apache Not Redirecting Non-WWW to WWW HTTPS

· 52CE 我爱测

I have a site, www.example.com , that I can't visit without entering the www. Using an Apache Virtual Host, I'm trying to make it so if non-www is entered, it's automatically redirected to www. If I try going to http://www.exampl…

问题原文

原帖链接 · GTS Joe · CC BY-SA 4.0

I have a site, www.example.com, that I can't visit without entering the www. Using an Apache Virtual Host, I'm trying to make it so if non-www is entered, it's automatically redirected to www.

If I try going to http://www.example.com, it redirects to https://www.example.com and works

If I try going to https://www.example.com, it also works.

However, the problem is:

If I enter http://example.com, it redirects to https://example.com and says:

This site can’t be reached Check if there is a typo in example.com.
If spelling is correct, try running Windows Network Diagnostics.
DNS_PROBE_FINISHED_NXDOMAIN

I get the same message if I try going to https://example.com

The problem is my site only works with "www." On non-www, how can I force www.? I was trying the following to no avail:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias example.com
    DocumentRoot /var/www/example.com/public/

    # Force non-www to www in HTTPS.
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    SSLEngine On
    SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem

    ErrorLog /var/log/httpd/example.com.error.log
    CustomLog /var/log/httpd/example.com.access.log combined
</VirtualHost>

已采纳解答

原帖链接 · tsc_chazz · CC BY-SA 4.0

I don't believe this is an issue with Apache. It's more likely that your authoritative DNS simply doesn't have an entry for the non-WWW version of your web site. For instance, nslookup www.example.com will return the IP address of your server. If you do nslookup example.com it should also return the IP address of your server; if it doesn't, fix that first.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-11-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。