使用nginx配置重定向比较方便,下面配置一个将根域名重定向到www域名,包括https的根域名重定向到www域名。开始配置
localhost.conf 文件
#处理80端口
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
#处理443端口
server {
listen 443 ssl;
server_name example.com;
# 切记 443 端口需要配置好ssl证书,公钥和私钥的路径
# ssl_certificate 公钥的路径
ssl_certificate example.com.pem;
# ssl_certificate_key 私钥的路径
ssl_certificate_key example.com.key;
# 301 重定向到https://www.example.com
return 301 https://www.example.com$request_uri;
}
# 上面已经过重定向80、443端口的根域名到www域名了。
# 下面配置www站的站点
server {
listen 443 ssl;
server_name www.example.com;
# ssl_certificate 公钥的路径
ssl_certificate example.com.pem;
# ssl_certificate_key 私钥的路径
ssl_certificate_key example.com.key;
# 项目根路径
root /www;
# 默认文件
index index.html index.php;
# 如果是thinkphp 框架,还需要配置pathinfo路径
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
}
}
# 如果是php程序,还需要配置以下代码段
location ~* \.php$ {
fastcgi_index index.php;
fastcgi_pass php:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
}
以上就是https协议的根域名进行重定向到https协议的www域名的nginx配置代码。如果仅仅是配置http,则无需配置443端口部分。