如何在nginx上提供静态资源时URL重写文件夹?

时间:2014-11-28 02:50:10

标签: nginx url-rewriting

我是Nginx的新手,我很难用我的小型PHP / Slim网站进行设置。

我的网站映射了以下网址:

//news/about/user/<user>,等等......

我几乎成功地解决了这个问题:

server {
  ...

  location / {
     if (!-e $request_filename) {
       rewrite ^(.*)$ /app.php break; #app.php is my main PHP file
     }

     fastcgi_... #PHP-FPM things here...
  }

  ...
}

但是,根据上面的代码,我无法映射/,而/assets/css/style.css中找不到的资产也无法加载。

我怎样才能使这个工作?

谢谢!

1 个答案:

答案 0 :(得分:0)

对静态资源使用单独的位置(文本,图片,音频,视频,文件,如果需要,可以添加更多扩展名)。并且您需要处理* .php的单独位置,从/ section中删除fastcgi配置。所以你将有3个位置(至少:)像这样。

location / {
  try_files $uri /app.php?$args;
}

location ~* \.(txt|ico|css|js|bmp|jpg|jpeg|gif|png|svg|swf|avi|mp4|webm|pdf|mel|rar|zip|bin)$ {
  expires max;
  access_log off;
  add_header Cache-Control public;
  # here can be more assets-optimized rules )
}

location ~ \.php$ {
  # minimal fastcgi configuration:
  if (!-e $request_filename) { rewrite ^(.*)$ /app.php break; } # Catch 404s that try_files miss
  fastcgi_pass unix:/var/run/php5-fpm.sock; # put your real backend here!
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}