首页主机资讯ubuntu nginx重定向规则怎么写

ubuntu nginx重定向规则怎么写

时间2026-01-16 04:09:06发布访客分类主机资讯浏览930
导读:在Ubuntu系统中,使用Nginx编写重定向规则通常涉及修改Nginx的配置文件。以下是一些常见的重定向规则示例: 1. 基本的重定向 将所有HTTP请求重定向到HTTPS: server { listen 80; ser...

在Ubuntu系统中,使用Nginx编写重定向规则通常涉及修改Nginx的配置文件。以下是一些常见的重定向规则示例:

1. 基本的重定向

将所有HTTP请求重定向到HTTPS:

server {
    
    listen 80;
    
    server_name example.com www.example.com;


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

    }

}

2. 重定向特定路径

将特定路径重定向到另一个路径:

server {
    
    listen 80;
    
    server_name example.com www.example.com;


    location /old-path {
    
        return 301 /new-path;

    }

}

3. 重定向子域名

将一个子域名重定向到另一个子域名:

server {
    
    listen 80;
    
    server_name subdomain1.example.com;


    location / {
    
        return 301 https://subdomain2.example.com$request_uri;

    }

}

4. 重定向端口

将HTTP请求从80端口重定向到443端口(HTTPS):

server {
    
    listen 80;
    
    server_name example.com www.example.com;


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

    }

}


server {
    
    listen 443 ssl;
    
    server_name example.com www.example.com;
    

    # SSL配置
    ssl_certificate /path/to/certificate.crt;
    
    ssl_certificate_key /path/to/private.key;


    # 其他配置
}

5. 重定向查询参数

将带有特定查询参数的请求重定向到另一个路径:

server {
    
    listen 80;
    
    server_name example.com www.example.com;


    location /old-path {

        if ($args ~* "param=value") {
    
            return 301 /new-path?param=newvalue;

        }

    }

}

6. 重定向所有请求到另一个域名

将所有请求重定向到另一个域名:

server {
    
    listen 80;
    
    server_name example.com www.example.com;


    location / {
    
        return 301 https://anotherdomain.com$request_uri;

    }

}
    

修改配置文件并重启Nginx

在修改完Nginx配置文件后,需要重新加载或重启Nginx服务以使更改生效:

sudo nginx -t  # 检查配置文件是否有语法错误
sudo systemctl reload nginx  # 重新加载配置文件
# 或者
sudo systemctl restart nginx  # 重启Nginx服务

请根据你的具体需求调整上述示例中的域名、路径和参数。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: ubuntu nginx重定向规则怎么写
本文地址: https://pptw.com/jishu/780879.html
Linux FTP服务器如何配置匿名访问 ubuntu nginx负载均衡实现方式

游客 回复需填写必要信息