用于url路由的nginx.conf 我正试图让index.php处理http路由,以便让我的应用程序保持restful。

用于url路由的nginx.conf 我正试图让index.php处理http路由,以便让我的应用程序保持restful。,php,nginx,url-routing,Php,Nginx,Url Routing,我在nginx.cong中使用了try_files指令,但没有起作用,我点击了/blabla,而不是通过index.php,它抛出了一个404。 这是我当前的nginx.conf <pre> user www-data; worker_processes 1; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024;

我在nginx.cong中使用了try_files指令,但没有起作用,我点击了/blabla,而不是通过index.php,它抛出了一个404。 这是我当前的nginx.conf

<pre>

user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    # multi_accept on;
}

http {
    include       /etc/nginx/mime.types;

    access_log  /var/log/nginx/access.log;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay        on;

    gzip  on;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
server {
 location /  {
   try_files $uri $uri/ /index.php;
}

}
   
}

</pre>

你可能想试试这样的东西,对我来说很有魅力:

server {
    listen 80;
    server_name example.com;
    index index.php;
    error_log /path/to/example.error.log;
    access_log /path/to/example.access.log;
    root /path/to/public;

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

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
    }
}
这将查找您的web根目录所在的位置。您的所有web可访问文件都位于此目录中。如果文件存在,它将带您访问该文件。如果没有,那么它会把你扔进@rules块。您可以使用regexp匹配更改url格式。但简而言之,.*匹配url中的任何字符串,并将您带到索引。我稍微修改了您编写的内容,将原始输入作为参数输入index.php。如果不这样做,您的脚本将不会有关于如何路由请求的任何信息

例如,转到/blabla将屏蔽url,但只要/blabla不是目录,就可以调出/index.php?param=blabla


希望这有帮助

非常感谢,基恩。不幸的是,即使有你的建议,在重新加载nginx之后,当点击/blabla/Ok时,我仍然得到404,这是可行的,但我需要指定服务器名和根目录,因为在指定服务器上下文时,还必须指定服务器名称和根指令。您可以将这两个规则合并到一个规则try\u文件$uri$uri//index.php?param=$request\u uri中,从而保存额外的位置块
server {
    listen 80;
    server_name example.com;
    index index.php;
    error_log /path/to/example.error.log;
    access_log /path/to/example.access.log;
    root /path/to/public;

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

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
    }
}