phpmod-rewritenginxrequest-uri

Nginx rewrite arguments


I use Nginx with my webserver, and don't fully understand how the rewrite works here. I got it working on Apache.

I use MVC based PHP project, and i want to use clean URL's as i have done with Apache.

www.domain.com/index.php?url=home/index works fine. www.domain.com/home/index does not work. As you can see, i want to have clean URL's like the last one.

I've tried several rewrites, and don't know if I should use try_files or rewrite. But I guess it's rewrite im after.

As I said, I'm still learning the rewrite. My server block looks like this:

server {

listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

root /usr/share/nginx/html/pub/;
index index.php index.html index.htm;

server_name localhost;

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

location @rewrite {
    rewrite ^/index.php?$arg_url /$arg_url permanent;
}

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

}

I thought my rewrite block made sense, but I guess it doesn't. Tried several rewrites, either I get 500 or 404 error. And as I said, I don't get rewrites yet. Need some help to get started.

Thanks in advance.


Solution

  • Not an expert with nginx either but I think you are looking for something like this:

    location / {                                                            
     index  index.html index.htm index.php;
     if (!-d $request_filename) {
      rewrite  ^/(.*)$ /index.php?url=$1  last;
      break;                                                  
     }
    }   
    

    Then you can remove that rewrite directive

    The rest of my config looks like this:

    location ~ \.php$ {
     root /var/www/path;
     fastcgi_split_path_info ^(.+\.php)(/.+)$;
     #try_files $uri=404;
     fastcgi_pass unix:/var/run/php5-fpm.sock;
     fastcgi_index index.php;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name
    
     include fastcgi_params;
     fastcgi_buffer_size 128k;
     fastcgi_buffers 2564k;
     fastcgi_busy_buffers_size 256k;
     fastcgi_temp_file_write_size 256k;
    
    }
    location ~ /\.git {
     denyall;
    }
    
    #Staticfileslocation
    
    location ~* ^.+.(swf|jpg|jpeg|gif|png|ico|css|bmp|js|zip)$ {
     expires max;
     root /var/www/path;
    }