Mario Fridrichovsky
Mario Fridrichovsky

Reputation: 47

nginx CSS break after adding rewrite from $ to $.php

If I will add the following line to my nginx configuration it will break my website and will run without CSS:

location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|svg|xml)$ {
  access_log        off;
  expires           30d;
}

location / {
    try_files $uri $uri/ $uri.php =404;
    rewrite ^/(.+)$ /$1.php last;
}

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

if I comment the rewrite condition everything will work fine.

What can I do to bring both things to work, the rewrite condition and the css style sheet?

Edit: I got a new problem, now all files like test.php work fine without writing .php, but folders like users/ won't work, I still reveive File not found, normaly it should take the index.php or index.html from the folder, how can I provide both functions? add .php to files and use inde.php/html from folder?

Upvotes: 3

Views: 751

Answers (2)

iquito
iquito

Reputation: 2555

You can separate the try_files and rewrite by replacing the location / block with the following two location blocks:

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

location @rewriterules { 
    rewrite ^/(.+)$ /$1.php last;
}

That way try_files goes first, and if no file is found there is a rewrite and .php is added to the request, which is then executed by the .php location block which should need no modification.

Upvotes: 2

Joe Beans
Joe Beans

Reputation: 294

Add the following block to your configuration to handle static files.

location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
  access_log        off;
  expires           30d;
  root /path/to/public/root;
}

Upvotes: 2

Related Questions