Nginx 301重定向

LNMP下的Nginx如果想将域名lnmp.org 301重定向到www.lnmp.org,同时www.lnmp.org已经添加上,可以按如下步骤修改 使用命令编辑器vinanowinscp图形管理软件编辑对应的虚拟主机,一般虚拟主机配置文件位于:/usr/local/nginx/conf/vhost/域名.conf ,如添加的域名是www.lnmp.org则配置文件是/usr/local/nginx/conf/vhost/www.lnmp.org.conf 在配置文件代码如下:

lnmp.org 301跳转到www.lnmp.org示例配置如下:

省略www.lnmp.org虚拟主机server配置
server {
listen 80;
server_name lnmp.org;
return 301 http://www.lnmp.org$request_uri;
}

如果是想让http强制跳转到https,把里面的http换成https就行。

http站点301跳转到https站点示例配置如下:

server {
listen 443 ssl;
server_name www.lnmp.org;
省略其他配置
}
server {
listen 80;
server_name lnmp.org;
return 301 https://www.lnmp.org$request_uri;
}

按上面例子修改完成后保存,执行:/etc/init.d/nginx restart 重启nginx,使其生效。
该设置不适用于Let’sEncrypt及其他需要http验证的SSL证书;如果使用DNS API方式可以使用这种设置方法。

如果是想让https://lnmp.org强制跳转到https://www.lnmp.org

可以在https的虚拟主机配置文件中root行或server_name行下面添加上

if ($host = 'lnmp.org') {
  return 301 https://www.lnmp.org$request_uri;
}

如果要设置对应域名的http跳到对应https站点上

如:http://lnmp.org 跳到 https://lnmp.org,http://www.lnmp.org 跳到 https://www.lnmp.org 上。
在对应域名的http虚拟主机配置文件中添加:return 301 https://$host$request_uri;

如果使用Let’sEncrypt免费SSL证书

使用的Let’s Encrypt的免费证书且使用http验证方式生成的SSL证书,如果你要想设置301,编辑要设置301域名的nginx虚拟主机配置文件,找到包含有listen 80;的server段,在

        location ~ /.well-known {
            allow all;
        }

这几行下面添加,如下配置:

        location / {
            return 301 https://$host$request_uri;
        }

保存,如果不设置会导致证书无法正常续期。
完整的适用于Let’sEncrypt的301跳转配置文件如下:

server
    {
        listen 80;
        #listen [::]:80;
        server_name lnmp.org www.lnmp.org;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/lnmp.org;

        location ~ /.well-known {
            allow all;
        }

        location / {
            return 301 https://$host$request_uri;
        }
    }

注意:以上所有更改nginx的配置都需要重启ngin生效。

20220511更新

今天发现又没有正确自动更新证书,于是乎登上终端,输入如下指令。

lnmp ssl add

然后按提示操作,结果不行,说timeout

估计又是没正确访问到需要challenge的地址

检查fivyex.com.conf

发现相比于前面最后一块代码,缺了如下两行

index index.html index.htm index.php default.html default.htm default.php;
root  /home/wwwroot/lnmp.org;

导致访问https://fivyex.com的时候没法找到正确的地址,自然也找不到正确的待challange的文件了

把这两行加上,再次运行

lnmp ssl add

即可成功更新证书,但是重启nginx的时候提示

[warn] conflicting server name

原因是lnmp ssl add实际上增加了一个新的server,只需要其中一个删掉就行

删的时候需要注意ssl证书的路径是否正确,然后自己添加的部分是否正确

转载自

https://lnmp.org/faq/lnmp-nginx-301-rewrite.html

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据