Nginx exactly ROOT directive (not anything) - regex

I have a RESTful server. I serve my static files with Nginx. I want the root url ( www.website.com, www.website.com/ ) to point to a static html file, and EVERY other request to be redirected to my RESTful server. What I have:
location / {
proxy_pass http://localhost:5000/;
}
location /static {
autoindex on;
alias "some location";
}
location /media {
autoindex on;
alias "some location";
}
What I need: a directive that redirects only the Root URL (not everything like /).

Nginx location directive has = modifier for that.
location = / {
# only request to '/' gets here
}
location / {
# all other goes here
}

Related

Partially using Vue with nginx

I'm trying to use both vue.js and Django with nginx. The issue is, that it still redirect my /subscriptions/ url to Django. Removing the '/' rule would make it work though. Is there a way to "skip" Django when the url matches 'custom'?
Basically, I would like to specify which links would be used with vue, and the rest with Django.
location = /custom/ {
root /home/django/project/frontend/dist;
index /index.html;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/django/project/project.sock;
}
The following will serve the files inside /home/django/project/frontend/dist/ if the path of the request starts with '/custom/'
location /custom/ {
root /home/django/project/frontend/dist/;
index /index.html;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/django/project/project.sock;
}
Here's the solution. For some reason it needs 2 slashes in the root.
root /home/django/tradeium/frontend/dist//;
index index.html;
location / {
include proxy_params;
proxy_pass http://unix:/home/django/project/project.sock;
}
location = /custom/ {
try_files $uri $uri/ index.html;
}

NGINX specify variable for specific directory and index file only

I am using fastcgi caching, and would like to specify which URLs the cache should be active on.
I use a rewrite rule to determine which controller file to access, and set any query parameters dynamically
I want to specify URLs in which the cache is activated, and those in which it is inactive, this is my code:
server {
listen 80;
server_name domain.com;
root /home/site/wwwroot;
set %skip_cache 1; #this is the variable that I want to set to 0 on specific URLS
location / {
try_files $uri $uri/ $uri.html #php;
}
location #php {
rewrite ^(/[^/]+)$ $1.php last;
rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
}
location /user/ {
set $skip_cache 0;
}
location /objects/ {
set $skip_cache 0;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_split_path_info ^(.+?\.php)(/.*)?$;
fastcgi_connect_timeout 300;
...etc...
#cache parameters
fastcgi_param FASTCGI_CACHE 1;
fastcgi_cache cfcache;
fastcgi_cache_valid 30s;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
add_header X-FastCGI-Cache $upstream_cache_status;
}
as you can see, the variable $skip_cache is set to 1 by default, and I would like to white list URLs for caching.
An example I would like cached is domain.com, domain.com/user/123 and domain.com/objects/456
Currently, if I browse to /user/123, the result is a 404 error, as I believe that location block with the variable setting is being used exclusively.
If you want to set a variable based on the original request, you should use a map directive with the $request_uri variable. See this document for details.
For example:
map $request_uri $skip_cache {
default 1;
~^/user/ 0;
~^/objects/ 0;
}
server {
...
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
...
}

Weird redirect with proxy_pass in if statement

I've a SPA (Single Page Application) site, let's say under https://example.com and an API for it under https://api.example.com
I want to serve server rendered content for specific useragents like googlebot, facebookexternalhit, etc.
So, if user goes to https://example.com/brandon/things it will get served SPA, but if bot goes to the same URL it will get served server rendered page with all proper meta and open graph tags.
My server rendered pages with proper matching are under https://api.example.com/ssr/
So for example if bot hits https://example.com/brandon/things it should get content from https://api.example.com/ssr/brandon/things
I almost got it working with nginx proxy_pass if statement to the Django application (which returns server rendered output) but unfortunately there's one edge case that makes it behave weirdly.
My implementation:
server {
listen 80;
server_name example.com; # url of SPA
index index.html;
root /srv/example_spa/public/dist; # directory of SPA index.html
# $ssr variable that tells if we should use server side rendered page
set $ssr 0;
if ($http_user_agent ~* "googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|facebot|twitterbot|developers\.google\.com|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|redditbot") {
set $ssr 1;
}
# location block that serves proxy_pass when the $ssr matches
# or if the $ssr doesn't match it serves SPA application index.html
location / {
if ($ssr = 1) {
proxy_pass http://127.0.0.1:9505/ssr$uri$is_args$args;
}
try_files $uri /index.html;
}
}
But there's the problem:
Everything works dandy and sweet, except one case.
User hits https://example.com/brandon/things/ and he gets SPA index.html - perfect.
User hits https://example.com/brandon/things and he gets SPA index.html - perfect.
Bot hits https://example.com/brandon/things/ and he gets server rendered page - perfect.
Bot hits https://example.com/brandon/things (without appended slash) and he gets redirected (301) to https://example.com/ssr/brandon/things - BAD BAD BAD
I've tried to make it work for couple of hours now without luck.
What would you suggest? I know if in nginx is evil, but I don't know how to make it work without it...
Any help is appreciated
You need to alter the redirects for proxy_pass
location / {
proxy_redirect http://127.0.0.1/ssr/ http://$host/ssr/;
proxy_redirect /ssr/ /;
if ($ssr = 1) {
proxy_pass http://127.0.0.1:9505/ssr$uri$is_args$args;
}
try_files $uri /index.html;
}
It turns out this was issue with my Django application redirect. I thought I had "APPEND_SLASH" option disabled, but it was enabled and made redirect when there was no slash. And it redirected without changing the host to https://api.example.com, but only URI part. Hence my confusion.
And I actually found two ways to fix that.
First, just use rewrite to append slash when there isn't one.
location / {
if ($ssr = 1) {
rewrite ^([^.]*[^/])$ $1/ permanent;
proxy_pass http://127.0.0.1:9505/ssr$uri$is_args$args;
}
try_files $uri /index.html;
}
Second, modify proxy_pass to always add / slash after $uri part and server side render application url config to accept two slashes at the end //'. It's a little hacky but has no side effects and works as it should.
Nginx config:
location / {
if ($ssr = 1) {
proxy_pass http://127.0.0.1:9505/ssr$uri/$is_args$args;
}
try_files $uri /index.html;
}
Django URL regex:
r'^ssr/(?P<username>[\w-]+)/(?P<slug>[\w-]+)(/|//)$'

Django Nginx X-Accel-Redirect for protected files on Webfaction

If you want to torment someone until the end of time, just get them to configure Django and Nginx X-Accel-Redirect. This is literally impossible, I have been trying for days.
I am trying to only allow certain files to be downloaded from logged in views in django using Nginx on webfaction. Here is what I have:
Custom Nginx app listening on port 27796 under /static. Here is the conf.
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 27796;
server_name myurl.com;
root /home/ucwsri/webapps/static_media_ucwsri_nginx;
location / {
autoindex on;
}
location ^.*/protected-files {
internal;
alias /home/ucwsri/webapps/static_media_ucwsri_nginx/protected;
}
All static content is in /home/ucwsri/webapps/static_media_ucwsri_nginx, and is being correctly served by this Nginx app.
The files I want protected are here:
/home/ucwsri/webapps/static_media_ucwsri_nginx/protected
Which is the alias listed under the location ^.*/protected-files block in Nginx.
The view simply makes an Http Response thus:
response = HttpResponse()
url = "/static/protected-files/some-file.pdf"
response['X-Accel-Redirect'] = url
return response
Where the 'some-file.pdf' file exists in
/home/ucwsri/webapps/static_media_ucwsri_nginx/protected
Whatever I try I get a 404 from Nginx when trying to get that file as a POST request that goes to that view. I have tried everything I can think of, every location combination block, nothing works. Always a 404.
Someone please put me out of my misery and tell me what I have done wrong. This is truly brutal for something seemingly so simple.
First, your location ^.*/protected-files is nonsense. I guess, you've missed ~ modifier, but even in that case it would be useless.
Second, you have not protected /protected/ folder. Direct request to /protected/some-file.pdf will download that file without any protection.
Third, you have /static/protected-files/some-file.pdf in X-Accel-Redirect, but you didn't mention any static folder before.
So, I would suggest following config:
server {
listen 27796;
server_name myurl.com;
root /home/ucwsri/webapps/static_media_ucwsri_nginx;
location / {
autoindex on;
}
location ^~ /protected/ {
internal;
}
And django should be:
response = HttpResponse()
url = "/protected/some-file.pdf"
response['X-Accel-Redirect'] = url
return response
Summary:
Protect real folder.
X-Accel-Redirect is URI, just think about it as if user put that URI in browser address bar. The only difference is that internal will allow access with X-Accel-Redirect while forbid direct user access from browser.

nginx and django - gettng cache-control to work

I am trying to get cache-comtrol to work.
In nginx I have the following:
location /static/ {
alias /home/ubuntu/workspace/mysite;
expires max;
add_header Cache-Control public;
}
in mysite dir I have static. In static I have the dirs for js, css, and images.
In the web browser I get 404 error. Images cant be found. If I remove location /static/ this site works but I have no cache-control.
How do I resolve?
If you use url like: http://your.page.com/static/image.gif then with your rules you get such uri (including alias directive):
/home/ubuntu/workspace/mysiteimage.gif;
So conclusion is that remove last / from location directive (it should be /static) or add at the end to alias directive / (so it will be as alias /home/ubuntu/workspace/mysite/;)
Other solution could be like:
location ~ (static/.*) {
alias /home/ubuntu/workspace/mysite/$1;
# ... rest of code here
}
Then you don't have to add static again in alias directive. You just use it as location param ($1 = static/.*).
Why that way? alias directive (alias doc) work as follow: it trims from requested url part matched in location directive end then, with what will stay, append to it own rule path. In your example from url /static/image.gif/ it will trim /static/ and to your alias path append only image.gif so it will look like I wrote: /home/ubuntu/workspace/mysiteimage.gif/`.