Nginx重写动态页面不起作用

时间:2014-04-17 23:46:08

标签: php nginx rewrite

我的网站中有一部分我希望包含许多文件,除以某些类别,每个类别都是自己的文件夹。但是,用户不必导航到包含http://example.com/subpage/?cat=random&page=stuff之类网址的网页,我更愿意重写网址以允许使用http://example.com/subpage/random/stuff

这样我就可以使用单个框架页面"其中包括我的网站需要加载的所有其他内容,并且只包含该主页中的请求文件(在此示例中为subpage.php。)

但是,在实现重写规则时,我遇到了一些问题,例如动态加载的文件无法检测主页中包含的php文件(导致我的服务器因500错误而窒息)或显示原始文本,但不包含主页面包含的CSS,jquery脚本或其他HTML文件。

以下是我的主页面处理URL并请求包含页面的部分:

if(!empty($_GET['cat']) && !empty($_GET['page'])) {
  $folder = $_GET['cat'];
  $page = $_GET['page'] . ".php";
  $pages = scandir($folder);
  unset($pages[0], $pages[1]);

  if(file_exists($folder . DIRECTORY_SEPARATOR . $page) && in_array($page, $pages)) {
    include("important-file.php");
    include($folder . DIRECTORY_SEPARATOR . $page);
  } else {
    header("HTTP/1.0 404 Not Found");
  }
} else {
  include("contents.php");
}

服务器抛出错误,因为第二个include语句加载的页面无法调用" important-file.php"中显示的函数。如果我将include语句移动到页面本身,那么只打印该页面的内容,没有我的网站的页眉/页脚,CSS或通常由"重要的内容打印的内容 - file.php"

以下是我的服务器使用的Nginx重写规则:

rewrite ^/([^/]*)/([^/]*)$ /subpage/?cat=$1&page=$2 last;

我已经清除了上面的许多无关代码,比如回显的div和其他HTML格式。我主要关注的是将我需要的页面包含在主页的主体中。

Nginx配置文件:

server {
  listen 80 default_server;
  listen [::]:80 ipv6only=on;

  root /usr/share/nginx/html;

  server_name localhost;

  error_page 403 /;
  error_page 404 /error/404.php;
  error_page 500 502 503 504 /error/50X.php;

  location / {
    try_files $uri $uri/ @no-extension;
    index index.html index.htm index.php;

    #allow 192.168.0.0/24;
    #allow 127.0.0.1;
    #deny all;
  }

  location /subpage {
    try_files $uri $uri/ @no-extension;
    index index.html index.htm index.php;

    rewrite ^/subpage/([^/]*)/([^/]*)$ /subpage/?cat=$1&page=$2 last;
  }

  # PHP Handler
  location ~ \.php$ {
    try_files $uri $uri/ =404;

    include fastcgi_params;
    fastcgi_pass php5-fpm-sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_intercept_errors on;
  }

  # Deny access to or drop hidden file access from logs
  location ~ /\. {access_log off; log_not_found off; deny all;}
  location ~ ~$  {access_log off; log_not_found off; deny all;}
  location = /robots.txt {access_log off; log_not_found off;}

  # Browser caching
  location ~* \.(js|css|png|jpg|jpeg|gif|ico|eot|woff|ttf|svg)$ {
    expires max;
    log_not_found off;
  }

  location @no-extension {
    rewrite ^(.*)$ $1.php last;
  }
}

0 个答案:

没有答案