如何使用nginx将js文件作为php提供?

时间:2017-10-11 22:42:03

标签: nginx

例如example.com/apple.js加载为php文件apple.js.php

用apache:

RewriteRule ^apple\.js$ apple.js.php [L]
RewriteRule ^banana\.js$ banana.js.php [L] 

你如何对nginx做同样的事?

这就是我尝试过并显示404错误。

server {
    server_name www.site.co.uk;

    root /var/www/site/public;

    access_log  /var/log/nginx/site.access.log;
    error_log  /var/log/nginx/site.error.log;

    listen 80;
    listen [::]:80;

    location ~ /apple.js {
        try_files $uri /apple.js.php;
    }

    location ~ /banana.js {
        try_files $uri /banana.js.php;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;

        try_files $fastcgi_script_name =404;

        set $path_info $fastcgi_path_info;
        fastcgi_param PATH_INFO $path_info;

        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param HTTPS on;
        include fastcgi.conf;
        }
}

1 个答案:

答案 0 :(得分:1)

以下rewrite规则允许使用PHP动态提供这些网址

www.site.co.uk/apple.js
www.site.co.uk/banana.js

Nginx服务器块

server {
  ...

  rewrite ^/apple\.js$  /apple.js.php;
  rewrite ^/banana\.js$ /banana.js.php;

  ...
}

banana.js.php

<?php

header("Content-Type: text/javascript; charset=utf-8");
echo "This is BANANA by PHP";

apple.js.php

<?php

header("Content-Type: text/javascript; charset=utf-8");
echo "This is APPLE by PHP";