3

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?

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

if I will only add your try_files without any rewrite, it will work for folders and names with endings, but if I type only test I will receive the php file as a download.
I edited my answer with a different solution to keep the rewrite, this should work as expected.
won't work, still 404, looks like he doesn't fall into the @rewriterule
404 for what file exactly? Because these location blocks will either find the static file or follow @rewriterules and try adding .php.
the folder users/ works, the file test.php works too, but the rewrite to test won't work.
|
2

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

2 Comments

thanks, this works for me, but can you please explain me what access_log and expires do? Are there additional file types to add? I added svg because I used lots of them.
@MarioFridrichovsky setting access_log to off makes sure that the http access logs for these files are not recorded. expires sets the HTTP Expires header to 30 days for web browsers to encourage static file caching on user's browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.