Why Nginx rewrite everything to index.php, is not working?

2.1k Views Asked by At

I have just started to experiment with Nginx, but I'm having troubles with the configuration. I would like to achieve the following:

  • I want every traffic to be redirected to index.php - so I can use routing to create clean URLs.

Si I'd like it to rewrite the URL. Before I've used Apache with this configuration:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

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

This Apache rule just redirected every traffic to index.php. I would like to achieve the same with Nginx.

I have this code so far, but it doesn't really wokrking. It gives me 502 errors and 403 errors.

server {
          error_log /var/log/nginx/vhost-error_log warn;
          listen *.*.*.*:80;
          listen [::]:80;
      server_name ***.com www.***.com;
          access_log /usr/local/apache/domlogs/***.com-bytes_log bytes_log;
          access_log /usr/local/apache/domlogs/***.com combined;
          root /home/***/public_html;
          #location / {
          location ~*.*\.(3gp|gif|jpg|jpeg|png|ico|wmv|avi|asf|asx|mpg|mpeg|mp4|pls|mp3|mid|wav|swf|flv|html|htm|txt|js|css|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|xls|xlsx|pdf|iso)$ {
          expires 1M;
          try_files $uri @backend;
          }

          location @backend {
          internal;
          proxy_pass http://*.*.*.*:8081;
          include proxy.inc;
      include microcache.inc;
          }

          location ~ /\.ht {
          deny all;
          }
          location / {
              set $page_to_view "/index.php";
              try_files $uri $uri/ @rewrites;
              root   /home/***/www/public_html/ ;
              index  index.php index.html index.htm;
          }

          location ~ \.php$ {
              include /etc/nginx/fastcgi_params;
              fastcgi_pass  127.0.0.1:9000;
              fastcgi_index index.php;
              fastcgi_param SCRIPT_FILENAME /home/***/www/public_html/$page_to_view;
          }

          # rewrites
          location @rewrites {
              if ($uri ~* ^/([a-z]+)$) {
                  set $page_to_view "/$1.php";
                  rewrite ^/([a-z]+)$ /$1.php last;
              }
          }
        }

I know this is a mix of the original config and something I've found on google. Can anyone please help me how should I make an useable file which does the job I'd need?

1

There are 1 best solutions below

0
On

try to change:

try_files $uri $uri/ @rewrites;

to:

try_files $uri $uri/ /index.php?q=$uri;

this will be the equivalent of your apache's rewrite

also, your copy/paste configuration probably doesn't make sense. better start from empty one. you need

location / {
  try_files $uri $uri/ /index.php?q=$uri;
  root ***;
}

and the \.php pieces to get started