菜刀短网址nginx 404错误

nginx短网址转发 by 老李菜刀 at 2025-10-03

参考:caidao.Net/dwzwt

问题分析

Nginx未配置PHP解析 - 直接返回404

缺少URL重写规则 - 无法处理/link这样的路径

文件路径问题 - Nginx权限或路径配置错误

解决方案

检查Nginx配置文件

在Nginx的站点配置中添加PHP支持:

server {
    listen 80;
    server_name your-domain.com;
    root /path/to/your/webroot;
    index index.php index.html;

    # PHP解析配置
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 根据实际PHP版本调整
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # URL重写规则 - 处理短链接
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # 特别处理短链接格式
    if (!-e $request_filename) {
        rewrite ^/([a-zA-Z0-9]+)$ /index.php?link=$1 last;
    }
}

使用npm管理器反代Docker版nginx-php后短网址跳转不了

# 以下为高级配置示例,请根据实际需求调整
location / {
    proxy_pass http://内网服务器IP:端口/;       # 替换为你的实际后端地址
    proxy_set_header Host $http_host;           # 传递原始主机头
    proxy_set_header X-Real-IP $remote_addr;    # 传递客户端真实IP
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme; # 传递原始协议 (http/https)
    proxy_set_header X-Forwarded-Host $http_host; # 传递原始主机和端口
    proxy_set_header X-Forwarded-Port $server_port; # 传递代理服务器访问端口

    # 处理重定向:确保后端服务产生的重定向响应也通过代理
    proxy_redirect http:// https://; # 如果强制HTTPS,可将HTTP重定向到HTTPS
    # 更精确地控制重定向,有时可能需要:
    # proxy_redirect ~^http://[^:]+:(\d+)/(.*) https://$http_host/$2;
}

最终代码,但文件夹要排除

location / {
    proxy_pass http://后端服务器IP:端口;

    # 必须的代理头
    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;
    proxy_set_header X-Forwarded-Host $host;

    # 简化重定向
    proxy_redirect http:// https://;

    # 短网址重写(保持原有逻辑)
    if (!-f $request_filename) {
        rewrite ^/([a-zA-Z0-9]+)$ /index.php?link=$1 break;
    }
}