nginx 上针对 css js 文件的重写规则不起作用

nginx 上针对 css js 文件的重写规则不起作用

我在 nginx 服务器上使用 laravel 框架来构建我的网站

我需要在 nginx 上应用重写规则

它是一个示例:

site.com/play/gamename/css.css --> site.com/uploads/games/gamename/css.css
or
site.com/play/gamename/js.js --> site.com/uploads/games/gamename/js.js

我需要知道如何定义规则来做到这一点?

我的网站根路径是

/var/www/html/siteuser/

根目录:

app
storage
public
-uploads
,...

在我的旧服务器中,使用 apache .htaccess:

RewriteCond %{REQUEST_URI} \.(jpg|png|css|js|appcache|xml|ogg|m4a)$
RewriteRule ^play/(.+) siteuser/public/uploads/games/$1 [L]

我测试了这个但是不起作用:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html/siteuser/public;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.php;

        server_name .site.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.php?$query_string;
                if ($uri ~ ".(jpg|png|css|js|appcache|xml|ogg|m4a)$"){
                        set $rule_0 1$rule_0;
                }    
        }
        if ($uri ~ ".(jpg|png|css|js|appcache|xml|ogg|m4a)$"){
                set $rule_0 1$rule_0;
        }
        if ($rule_0 = "1"){
                rewrite ^/play/(.+) /siteuser/public/uploads/games/$1 last;
        }


        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }
}

答案1

rewrite根本不应该对此使用 a。而应使用aliased location

例如:

location ~* ^/play/.*\.(jpg|png|css|js|appcache|xml|ogg|m4a)$ {
    alias /var/www/html/siteuser/public/uploads/games/;
}

这将仅为以 开头的 URL 提供具有给定文件扩展名的静态文件/play/,这些文件来自 中给出的路径alias,使用不区分大小写的匹配。/play/在此配置中,任何 PHP 代码都无法从内部运行。

相关内容