在 LNMP(Linux + Nginx + MySQL + PHP) 环境下设置 301 重定向,通常是在 Nginx 配置文件 里完成。下面按常见场景给你详细说明。
LNMP 的 Nginx 配置一般在:
/usr/local/nginx/conf/
站点配置文件通常在:
/usr/local/nginx/conf/vhost/你的域名.conf
(LNMP 一键包默认结构)
✅ 推荐做法
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
# 正常站点配置
}
server {
listen 80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 80;
server_name old.com www.old.com;
return 301 https://new.com$request_uri;
}
location = /old.html {
return 301 /new.html;
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/fullchain.pem;
ssl_certificate_key /path/privkey.pem;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name www.example.com;
ssl_certificate /path/fullchain.pem;
ssl_certificate_key /path/privkey.pem;
root /home/wwwroot/example.com;
index index.php index.html;
}
nginx -t # 检查配置
lnmp nginx reload
或:
systemctl reload nginx
✅ 301 是永久重定向,浏览器会缓存
✅ 不要多个 return 301 形成死循环
✅ 使用 return 301 比 rewrite 性能更好
✅ 调试时可用 curl -I http://域名 查看状态码
curl -I http://example.com
应看到:
HTTP/1.1 301 Moved Permanently
Location: https://www.example.com/
如果你愿意,可以把 你的 LNMP 版本 + 域名结构 + 想实现的跳转规则 发给我,我可以帮你直接写一份完整的 vhost 配置。