大网数据广告活动
服务器运维问答

NGINX - Forward everything to a php script

· 52CE 我爱测

I'm trying to forward every request to the same php script. I came up with this configuration: server { listen 80; server_name example.com; root /var/www/html; index api.php; location / { try_files $uri /api.php$is_args$args; } l…

问题原文

原帖链接 · guidev · CC BY-SA 3.0

I'm trying to forward every request to the same php script.

I came up with this configuration:

server {
    listen 80;
    server_name example.com;

    root /var/www/html;

    index api.php;

    location / {
        try_files $uri /api.php$is_args$args;
    }

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index api.php;
        fastcgi_pass 127.0.0.1:9000;
    }
}

While it works, it still allows direct access to resources if the correct $uri is provided.

If I try to change the first location block to this:

location / {
    try_files /api.php$is_args$args =404;
}

It doesn't work, always returns 404.

已采纳解答

原帖链接 · Pothi Kalimuthu · CC BY-SA 3.0

server {
    server_name example.com;

    root "/var/www/html";

    location / {
        include "fastcgi_params";
        fastcgi_param SCRIPT_FILENAME $document_root/api.php;
        fastcgi_param SCRIPT_NAME api.php;
        fastcgi_index api.php;
        fastcgi_pass 127.0.0.1:9000;
    }
}

If the aim is to forward all the requests to a single PHP script and if that single PHP script is known in advance by its name, then we don't need a separate location block. Only one location block that sends all the requests to that known PHP script is enough.

fastcgi_split_path_info is not needed, when the PHP script to be executed is not known in advance and is available only as part of the URI.

Also, try_files $uri =404 isn't needed since that known PHP script is already available at a fixed / known place.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-01-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。