Nginx - 重写后找不到php文件

时间:2017-08-23 07:49:32

标签: php nginx url-rewriting

我正在尝试重写 / assets / * - >到/ theme / theme_1 / * 。 重写URL适用于除.php文件之外的所有文件。

示例文件结构:

  • /theme/theme_1/images/image.jpg
  • /theme/theme_1/images/user.jpg
  • /theme/theme_1/ajax/register.php
  • /theme/theme_1/ajax/read.php

问题是PHP文件,我用这个url获得了404: wget http://example.com/assets/ajax/read.php。 使用完整路径http://example.com/theme/theme_1/ajax/read.php

找到(200)文件

所有其他文件工作正常(200): wget http://example.com/assets/images/image.jpg

nginx config:

server {
  listen 80 default_server;

  root /var/www/html;
  index index.php index.html
  server_name mysite.com;

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
  }

  location /assets {
    rewrite ^/assets/(.*) /theme/theme_1/$1 break;
  }

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

1 个答案:

答案 0 :(得分:0)

好的,你应该试试这个

  location /assets/ {
    alias /var/www/html/theme/theme_1/;
  }

如果不起作用,请尝试

  location /assets/ {
    alias /var/www/html/theme/theme_1/;
    try_files $uri $uri/ /index.php?$args;
  }

修改-1

第二次看,我意识到前面的答案不会起作用,因为~ \.php {块会捕获php扩展名的所有内容,而另一个assets块永远不会被调用。因此解决方案是将重写嵌套在php块中。所以使用

  location ~ \.php$ {
    rewrite ^/assets/(.*)$ /theme/theme_1/$1;

    include snippets/fastcgi-php.conf;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
  }