如何在 Nginx 中将单个 .js 扩展名文件重写并解析为 php

如何在 Nginx 中将单个 .js 扩展名文件重写并解析为 php

我的请求如下

domain.com/lib/browser/detect.js

现在我想在内部服务/lib/browser/detect.php

我的 Nginx 配置如下

location = /lib/browser/detect.js {
        try_files non-existent /lib/browser/detect.php;
}

location ~ \.php$ {
        fastcgi_split_path_info ^(.+?\.php)(/.*);
        fastcgi_read_timeout 900s;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Nginx 强制我的浏览器下载此文件。

答案1

尝试使用rewrite指令而不是try_files因为它仅用于服务器静态文件。

类似这样的事情可能会做到这一点:

location = /lib/browser/detect.js {
    rewrite .* /lib/browser/detect.php;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+?\.php)(/.*);
    fastcgi_read_timeout 900s;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

在这种情况下,它rewrite可能匹配任何内容,因为它已经位于精确匹配位置块内。您还可以在指令中进行匹配rewrite,然后将其从位置块中取出并放入服务器块中,就像我在此处的测试中所做的那样:

server {
  listen 80 default_server;
  root /var/www/;
  rewrite /detect.js /detect.php;
  location / {
     try_files $uri $uri/ =404;
  }
  location ~ \.php$ {
    include /etc/nginx/fastcgi.conf;
    fastcgi_pass 127.0.0.1:9000;
  }
}

这是 alpine linux 上 nginx 和 php-fpm 包的默认配置。fastcgi.conf 文件的内容如下:

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;

答案2

到目前为止我发现的唯一方法就是这个

location = /lib/browser/detect.js {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME /path/to/lib/browser/detect.php;
    fastcgi_param PATH_INFO detect.php;
}

相关内容