非 www 到 www apache2 Letsencrypt certbot

non www to www apache2 Letscrypt certbot

我想将我的非 www 重定向到 www 。 SSL 工作正常并且 url 都可以与 ssl 一起正常工作。 https://example.com https://www.example.com 两者都有效,但我想将 https://example.com 重定向到 https://www.example.com

我正在使用 AWS ec2 中的 lamp-server 并使用 certbot 进行 ssl。

我的 apache 配置。

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

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

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>
RewriteEngine on
RewriteCond %{SERVER_NAME} =example.com [OR]
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

我尝试了很多在线教程但没有任何帮助,在此先感谢您的帮助或支持。

尝试(注意:如果不删除以#开头的注释,Apache可能会抛出错误):

# turns on the rewrite engine
RewriteEngine On
# checks if domain is not www.example.com
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
# redirects to www.example.com
RewriteRule ^ https://www\.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# the above is enough for 443 VirtualHost

# checks if https is not on
RewriteCond %{HTTPS} !on
# redirects to https on the same domain
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 

因此,您的完整配置:

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

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

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^ https://www\.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTPS} !on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

将以下内容添加到 <VirtualHost *:443> 配置中:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^ https://www\.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]