# Nginx教程 - 7 return跳转

在 Nginx 配置中,return 指令用于立即终止处理并返回指定的状态码或重定向 URL。

# 7.1 使用示例

# 1 基本语法

return code;
return code URL;
return URL;
1
2
3

# 2 返回状态码

返回一个简单的状态码,比如 403 Forbidden 或 404 Not Found:

server {
    listen 80;
    server_name localhost;

    location /admin {
        return 403;
    }

    location /not-found {
        return 404;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

访问效果:

# 3 返回状态码和消息体

返回一个状态码和一个消息体(通常与 200 状态码一起使用):

server {
    listen 80;
    server_name localhost;

    location / {
        add_header Content-Type text/plain;  # 提示浏览器返回的是纯文本,否则浏览器可能会提示下载
        return 200 "Hello, world!";
    }
}
1
2
3
4
5
6
7
8
9

访问效果:

# 4 重定向请求

什么是重定向?

重定向就是浏览器请求 http://www.doubibiji.com/abc,如果服务器进行重定向,会返回HTTP响应,包含状态码(301 或 302)以及 Location 头部,指向新的URL,例如 http://www.doubibiji.com/bcd,那么浏览器根据返回的 Location 和 URL,会重新发起一个请求去请求 http://www.doubibiji.com/bcd


使用 301 永久重定向或 302 临时重定向将请求重定向到另一个 URL:

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

    # 将请求 https://www.doubibiji.com
    location / {
        return 301 https://$server_name$request_uri;
    }
}
1
2
3
4
5
6
7
8
9
  • location / { return 301 https://$server_name$request_uri; }
    • 任何对该服务器的请求都会被重定向。
    • $server_name 是服务器名变量,在这里为 www.doubibiji.com
    • $request_uri 是请求的 URI,包括路径和查询字符串。

当用户访问 http://www.doubibiji.com 时,浏览器会被重定向到 https://www.doubibiji.com ;用户访问 http://www.doubibiji.com/some/path 时,会被重定向到 https://www.doubibiji.com/some/path。也就是说 Nginx 配置会将所有的 HTTP 请求将被重定向到 HTTPS。

返回的状态码为 301(永久重定向),表示资源永久移动到新位置。


一般情况下,如果我们的站点是 https 请求的,那么会将 http 的请求重定向到 https,确保所有访问都是通过安全的 HTTPS 协议。

下面是可能会用到的配置:

server {
    listen 80;  # 监听http的80端口
    server_name www.doubibiji.com;

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

server {
    listen 443 ssl;  # 监听https的443端口
    server_name www.doubibiji.com;

    ssl_certificate /path/to/ssl_certificate.crt;  # https证书路径
    ssl_certificate_key /path/to/ssl_certificate_key.key;  # 私钥路径

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

https 的其他配置,在后面的 https 配置中再讲。