nginx 配置

二、常见路由规则配置示例

1. 基本路由转发(反向代理)

将特定路径转发到其他服务:

location /api/ {
    proxy_pass
        proxy_pass http://127.0.0.1:3000/;  # 转发到本地3000端口
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

2. 伪静态路由(适合 PHP 框架如 Laravel、ThinkPHP)

location / {
    if (!-e $request_filename) {
        rewrite  ^(.*)$  /index.php?s=$1  last;  # 转发到index.php处理
        break;
    }
}

3. 静态文件路由优化

# 处理静态文件
location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ {
    expires 30d;  # 设置缓存30天
    add_header Cache-Control "public, max-age=2592000";
    access_log off;  # 不记录静态文件访问日志
}

4. 特定路径重定向

# 将/http重定向到/https
location /http {
    return 301 /https$request_uri;
}

# 将根路径重定向到/admin
location = / {
    return 302 /admin;
}

5. 限制特定 IP 访问

location /admin/ {
    allow 192.168.1.100;  # 允许特定IP
    deny all;  # 拒绝其他所有IP
}
posted @ 2025-08-03 16:21  Lafite-1820  阅读(13)  评论(0)    收藏  举报