Nginx try_files 和别名

Nginx try_files 和别名

我有这样的配置:

server {
    server_name app.local;
    index index.php;

    location /api/v1 {
        alias /app/api/v1/code;

        try_files $uri /api/v1/index.php$is_args$args;

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass api-v1-php:9000;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            fastcgi_param SCRIPT_FILENAME $request_filename;
        }
    }
}

删除外部 try_files 后,似乎找到了 index.php,但我需要保留每个请求(例如 app.local/api/v1/test)都由 index.php 处理的行为。我该如何保持这种状态?这是漏洞

答案1

这是适用于 Linux Ubuntu 的带有 php7.4-fpm 的 nginx 的工作配置。

fastcgi.conf

# You can use NGINX to "sanitize" the input to the application by setting the HTTP_PROXY FastCGI parameter to
# an empty string. This removes the parameter completely from the FastCGI request.
fastcgi_param  HTTP_PROXY         "";
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

nginx.conf

# handle .php
location ~ \.php$ {
  # 404
  try_files           $uri $uri/ =404;
  
  # default fastcgi_params
  include             fastcgi.conf;
  
  # fastcgi settings
  fastcgi_pass        /run/php/php7.4-fpm.sock;
  fastcgi_index       index.php;
  fastcgi_buffers     8 16k;
  fastcgi_buffer_size   32k;
}

相关内容