1. 程式人生 > 其它 >Apache配置不帶www跳轉到帶www的域名地址

Apache配置不帶www跳轉到帶www的域名地址

 利用 Apache 環境的 .htaccess 偽靜態 301 跳轉,達到訪問不帶 www 的網址時會自動跳轉到帶 www 的網址。

1、確認是否開啟rewrite重寫模組

配置檔案一般位於/etc/httpd/config/httpd.conf

找到(沒有就新增)去掉#號

#LoadModule rewrite_module modules/mod_rewrite.so

2、設定AllowOverride

預設網站實際目錄是 /var/www/html的情況下,找到AllowOverride

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

3.修改.htaccess

(1)使用 vi 命令在網站的根目錄新建一個 .htaccess 檔案(如果有就編輯)

vim /var/www/html/.htaccess

(2)在裡面新增如下內容:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^xxx.com [NC]
    RewriteRule ^(.*)$ https://www.xxx.com/$1 [L,R=301]
</IfModule
>

xxx.com為你的域名地址

(3)儲存後重啟 Apache 伺服器

systemctl start httpd.service #啟動
systemctl stop httpd.service #停止
systemctl restart httpd.service #重啟