简体   繁体   中英

nginx.conf for url routing

I'm trying to have my index.php to handle http routing so make my app restful.

I've used the try_files directive within nginx.cong but did'nt work, I hit /blablabla and instead of going through index.php it throws a 404. Here's my current 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>

You might want to try something like this, works like a charm for me:

location / { 
    try_files $uri $uri/ @rules; 
} 

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

This looks for the location at / which is your web root. All of your web accessible files are found in this directory. If a file exists, it'll take you to that file. If not, then it'll throw you into the @rules block. You can use regexp matching to vary your url formatting. But in short, the (.*) matches any string in your url and takes you to your index. I modified what you had written slightly to feed the original input in to index.php as a parameter. If you don't do this, your script won't have any info about how to route the request.

For example, then going to /blablabla will mask the url but pull up /index.php?param=blablabla so long as /blablabla isn't a directory.

Hope this helps!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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