【问题标题】:Why Nginx rewrite everything to index.php, is not working?为什么 Nginx 将所有内容都重写为 index.php,不起作用?
【发布时间】:2013-12-31 15:17:33
【问题描述】:

我刚刚开始尝试使用 Nginx,但是我在配置方面遇到了问题。我想实现以下目标:

  • 我希望将所有流量重定向到 index.php - 这样我就可以使用路由来创建干净的 URL。

Si 我希望它重写 URL。在我使用 Apache 之前的配置:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ index.php?q=$1 [QSA,L]

这条 Apache 规则只是将所有流量重定向到 index.php。我想用 Nginx 实现同样的目标。

到目前为止,我有这段代码,但它并没有真正起作用。它给了我 502 个错误和 403 个错误。

server {
          error_log /var/log/nginx/vhost-error_log warn;
          listen *.*.*.*:80;
          listen [::]:80;
      server_name ***.com www.***.com;
          access_log /usr/local/apache/domlogs/***.com-bytes_log bytes_log;
          access_log /usr/local/apache/domlogs/***.com combined;
          root /home/***/public_html;
          #location / {
          location ~*.*\.(3gp|gif|jpg|jpeg|png|ico|wmv|avi|asf|asx|mpg|mpeg|mp4|pls|mp3|mid|wav|swf|flv|html|htm|txt|js|css|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|xls|xlsx|pdf|iso)$ {
          expires 1M;
          try_files $uri @backend;
          }

          location @backend {
          internal;
          proxy_pass http://*.*.*.*:8081;
          include proxy.inc;
      include microcache.inc;
          }

          location ~ /\.ht {
          deny all;
          }
          location / {
              set $page_to_view "/index.php";
              try_files $uri $uri/ @rewrites;
              root   /home/***/www/public_html/ ;
              index  index.php index.html index.htm;
          }

          location ~ \.php$ {
              include /etc/nginx/fastcgi_params;
              fastcgi_pass  127.0.0.1:9000;
              fastcgi_index index.php;
              fastcgi_param SCRIPT_FILENAME /home/***/www/public_html/$page_to_view;
          }

          # rewrites
          location @rewrites {
              if ($uri ~* ^/([a-z]+)$) {
                  set $page_to_view "/$1.php";
                  rewrite ^/([a-z]+)$ /$1.php last;
              }
          }
        }

我知道这是原始配置和我在谷歌上找到的东西的混合体。谁能帮助我如何制作一个可以完成我需要的工作的可用文件?

【问题讨论】:

    标签: redirect url-rewriting nginx vhosts


    【解决方案1】:

    尝试改变:

    try_files $uri $uri/ @rewrites;
    

    到:

    try_files $uri $uri/ /index.php?q=$uri;
    

    这将相当于你的 apache 的重写

    另外,您的复制/粘贴配置可能没有意义。最好从空的开始。你需要

    location / {
      try_files $uri $uri/ /index.php?q=$uri;
      root ***;
    }
    

    \.php 开始使用

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2018-08-27
      相关资源
      最近更新 更多