nginx.conf 用于 URL 路由


nginx.conf for url routing

我正在尝试让我的索引.php来处理http路由,所以让我的应用程序变得安静。

我在nginx.cong中使用了try_files指令,但没有工作,我点击了/blablabla,而不是通过索引.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>

你可能想尝试这样的东西,对我来说就像一个魅力:

location / { 
    try_files $uri $uri/ @rules; 
} 
location @rules { 
    rewrite ^/(.*)$ /index.php?param=$1; 
}

这将查找/的位置,这是您的 Web 根目录。您所有 Web 可访问的文件都可以在此目录中找到。如果文件存在,则会将您带到该文件。如果没有,那么它会把你扔进@rules块。您可以使用正则表达式匹配来改变您的 URL 格式。但简而言之,(.*)匹配 url 中的任何字符串,并将您带到索引。我稍微修改了您编写的内容,以将原始输入作为参数输入索引.php。如果不这样做,脚本将不包含有关如何路由请求的任何信息。

例如,转到 /blablabla 将屏蔽 url,但只要/blablabla不是目录,就会拉出/index.php?param=blablabla

希望这有帮助!

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;
    }
}