nginx + php 7 + $_GET params + Homestead

Byron Valdivieso asked:

My .htaccess is:

# nginx configuration 
location / { 
if (!-e $request_filename){ 
rewrite ^(.+)$ /index.php?url=$1 break; 
} 
}

I have nginx configured like this:

server {
listen 80;
listen 443 ssl http2;
server_name prueba_nginx.net;
root "/home/vagrant/Code/prueba_nginx/public";

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/prueba_nginx.net-error.log error;

sendfile off;

client_max_body_size 100m;

location ~ .php$ {
    fastcgi_split_path_info ^(.+.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    fastcgi_intercept_errors off;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
}

If I call: http://prueba_nginx.net/a/b/c

and I run the php commant: echo $_GET[‘urlĀ“] it must return: : a/b/c
but currently it is returning: empty.

PHP:

echo "n".'$_GET'."n"; var_dump($_GET);

If I made the test with apache it works perfect:

RewriteEngine On
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteCond  %{REQUEST_FILENAME} !-f 
RewriteCond  %{REQUEST_FILENAME} !-l 

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

what is the problem? Are there into the transformation from apache to nginx an error?

My answer:


You’ve got at least two problems I can see.

First:

# nginx configuration 
location / { 
if (!-e $request_filename){ 
rewrite ^(.+)$ /index.php?url=$1 break; 
} 
}

This is redundant and conflicts with the earlier defined location in nginx.conf. It should be disabled or removed.

Second:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Unlike what you appear to have in .htaccess, try_files is the correct way to do this. But, you aren’t providing the URL in the format that you want, and you only need to fix that.

location / {
    try_files $uri $uri/ /index.php?url=$uri;
}

Of course, you should instead do what most people do, and don’t do any special preprocessing in nginx. Instead, you get the request URI from the environment in $_SERVER['REQUEST_URI']. Which is of course best practice.

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

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.