简体   繁体   English

用PHP和重写规则的nginx

[英]nginx with php and rewrite rule

I'd like to set my nginx server with php, and a simple rewrite rule. 我想用php和一个简单的重写规则设置我的nginx服务器。 I tried to make a rewrite rule, that any urls which points to non existing file or directory, rewrites to /index.php?q=. 我试图制定一个重写规则,将指向不存在的文件或目录的所有URL都重写为/index.php?q=。 I created this nginx.conf: 我创建了这个nginx.conf:

events {
}

http {
  include fastcgi.conf;
  server {
    listen          80;
    server_name     www.example.com;
    index           index.php;
    root            /var/www/html/www.example.com;
    location / {
      index     index.php;
      if (!-f $request_filename) {
        rewrite ^/(.*)$ /index.php?q=$1 last;
      }
      if (!-d $request_filename) {
        rewrite ^/(.*)$ /index.php?r=$1 last;
      }
    }
    location ~ \.php {
      try_files $uri =404;
      fastcgi_pass 127.0.0.1:9999;
    }
  }
}

This works, but not in every case. 这可行,但并非在每种情况下都可行。 It perfectly rewrites utls like tihs: 它像tihs一样完美地重写了utls:

http://www.example.com/111/222/333 http://www.example.com/111/222/333

But two case not works as i want: 但是两种情况不符合我的要求:

http://www.example.com/111/222/333.php http://www.example.com/111/222/333.php

drops 404 error. 丢弃404错误。

And www.example.com/forum/index.php exists, so the www.example.com/forum/index.php executes index.php in forum directory, this is fine. 并且存在www.example.com/forum/index.php,因此www.example.com/forum/index.php在论坛目录中执行index.php,这很好。 But www.example.com/forum url rewrites to /index.php, not execute index.php in forum directory as i want. 但是www.example.com/forum url重写为/index.php,而不是我想要在论坛目录中执行index.php。

How can i solve this two problem? 我该如何解决这两个问题?

Thank you! 谢谢!

您的配置绝对错误,请用单行替换位置/内容:

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

如果要重定向到特定目录中的索引文件,则需要将重定向的格式设置为类似以下格式

rewrite ^/((.*/)*)(.*)$ /$1index.php?q=$3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM