ERR_CONNECTION_TIMED_OUT when calling backend NodeJS server behind VPN - node.js

I just created a website in reactJS (create-react-app) with a login possibility.
I configured autosigned SSL certificates with letsencrypt, added some DNS entries for HSTS and everything that make my website properly traffic-encrypted. My website is running on port 3001 (front-end) and my nodeJs backend is up on port 3000.
Everything works fine, however when some people try to connect to my website behind some VPN (not all of them), they see the page of my app (front-end) but when they try to login (connection to back-end), they get an ERR_CONNECTION_TIMED_OUT.
I cannot reproduce the bug because I do not have such VPN (with my NordVPN its working ok). So I would like you to help me to discover where this problem stems from.
Here is my nginx config file:
# xxx.fr nginx config file
user xxx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
}
http {
upstream frontends {
server xxx.fr:3001;
}
charset utf-8;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
keepalive_timeout 65;
proxy_read_timeout 200;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
gzip on;
gzip_min_length 1000;
gzip_proxied any;
gzip_types text/html text/css text/xml
application/x-javascript application/xml
application/atom+xml text-javascript;
proxy_next_upstream error;
#include /etc/nginx/sites-enabled/*;
server {
# default_server;
#listen [::]:80;
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload ';
#add_header Content-Security-Policy "default-src 'self';";
server_name xxx.fr www.xxx.fr;
client_max_body_size 50M;
location ^~ /build/static {
root /home/xxx/x/public;
index index.html;
if ($query_string) {
expires max;
}
}
location = /favicon.ico {
rewrite (.*) /public/favicon.ico;
}
location = robots.txt {
rewrite (.*) /public/robots.txt;
}
location / {
proxy_pass_header Server;
#add_header Strict-Transport-Security "max-age=31536000; includeSubDomains, preload" always;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
proxy_set_header X-Scheme $scheme;
proxy_pass http://frontends;
proxy_ssl_name $host;
proxy_ssl_server_name on;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/xxx.fr/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xxx.fr/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.xxx.fr) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = xxx.fr) {
return 301 https://$host$request_uri;
} # managed by Certbot
#listen 80;
server_name xxx.fr www.xxx.fr;
return 404; # managed by Certbot
}
}
And in my nodeJS server (back-end), I have the following header set:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Credentials", true);
// res.header("Access-Control-Allow-Credentials", "true");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
next();
});
Can anyone tell me how to fix the ERR_CONNECTION_TIMED_OUT ?
Thank you so much

Related

Cherrypy NGINX error: 403 directory index of /some/path is forbidden

I am running NGINX on an Ubuntu 18.04 x64 Digital Ocean server. I have a Cherrypy app running directly on the Ubuntu server. I am trying to use NGINX to proxy_pass to my Cherrypy app for a specific route. The proxy_pass appears to be working, but I am getting a 403 Forbidden error when I try to POST to the route. The Cherrypy route works with the Python requests POST request when I test it locally, but doesn't work when I send the request through NGINX with the proxy_pass.
Cherrypy is in a Pipenv virtual environment. To run it I run Python3 app.py.
Here's the error in the NGINX error log:
2019/10/17 20:51:50 [error] 29574#29574: *51 directory index of "/mnt/media_storage/media_root/media/monday/monday-file-upload/" is forbidden, client: 73.14.140.118, server: media.bscs.org, request: "GET /monday/monday-file-upload/ HTTP/1.1", host: "media.bscs.org"
Here's my NGINX config:
# Microcaching
proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;
# Cache in browser
# Expires map
map $sent_http_content_type $expires {
default off;
text/html epoch;
text/css 30d;
application/javascript 30d;
~image/ 30d;
}
upstream apps {
server 127.0.0.1:8080;
}
server {
listen 80;
listen [::]:80;
server_name media.bscs.org;
rewrite ^/(.*) https://media.bscs.org/$1 permanent;
}
server {
listen *:443 ssl http2;
listen [::]:443 ssl http2;
server_name media.bscs.org;
root /mnt/media_storage/media_root/media;
charset utf-8;
client_max_body_size 1000M;
# Gzip/compress text-based assets
gzip on;
gzip_http_version 1.0;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
gzip_types text/plain text/html text/css application/json application/x-javascript text/xml application/xml text/javascript application/javascript image/svg+xml;
gzip_disable "MSIE [1-6]\.";
# make sure gzip does not lose large gzipped js or css files
# see http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl
gzip_buffers 16 8k;
# Microcaching
proxy_cache cache;
proxy_cache_valid 200 1s;
# Cache in browser
expires $expires;
ssl on;
ssl_ciphers "my-cipher";
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
add_header X-Content-Type-Options nosniff;
add_header 'Access-Control-Allow-Origin' '*';
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver_timeout 5s;
ssl_certificate /etc/nginx/ssl/cert_chain.crt;
ssl_certificate_key /etc/nginx/ssl/STAR.bscs.org.key;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
location = /favicon.ico {
access_log off;
log_not_found off;
sendfile on;
sendfile_max_chunk 1m;
}
location ~* \.(gif|jpg|jpeg|png|js|css)$ {
log_not_found off;
access_log off;
sendfile on;
sendfile_max_chunk 1m;
}
location /media/ {
alias /mnt/media_storage/media_root/media/;
location /media/monday/monday-file-upload/ {
alias /mnt/media_storage/media_root/media/monday/monday-file-upload/;
proxy_pass http://apps/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
# Redirects
rewrite ^/tech-report/2018-1/2018-1.html$ https://bscs.org/resources/reports/designing-citizen-science-for-both-science-and-education-a-workshop-report/$1 permanent;
}
Here's my post request in with Python requests:
def uploadFileToMediaServer(uploaded_file_local_path):
with open(uploaded_file_local_path, 'rb') as f:
files = {'uploaded_file': f}
r = requests.post('https://media.bscs.org/monday/monday-file-upload', files=files)
print(r.request.url, file=sys.stderr)
print(r.request.headers, file=sys.stderr)
return r
Here's my Cherrypy app:
import cherrypy
from cherrypy.process.plugins import Daemonizer
config = {
'global': {
'server.socket_host': '127.0.0.1',
'server.socket_port': 8080,
'server.thread_pool': 8,
'server.max_request_body_size': 0,
'server.socket_timeout': 60
}
}
class App:
#cherrypy.expose
def index(self, uploaded_file):
try:
with open('../uploads/{}'.format(uploaded_file.filename), 'wb') as f:
while True:
data = uploaded_file.file.read(8192)
if not data:
return {'message': 'File failed to upload'}
f.write(data)
return {'message': 'File uploaded successfully'}
except Exception:
cherrypy.log(Exception, traceback=True)
if __name__ == '__main__':
d = Daemonizer(cherrypy.engine)
d.subscribe()
cherrypy.tree.mount(App(), "/", config)
cherrypy.engine.start()
cherrypy.engine.block()

loading assets infinitely on a nginx for nodejs application whose resources are compiled with webpack

I try to put a nodejs application in production using a nginx server when I test locally everything works fine but when I put on line I have an infinite load of some particular assets
here is my nodejs configuration file
upstream beauteadom_me {
server localhost:3000;
}
server {
listen 80;
listen [::]:80;
server_name beauteadom.me www.beauteadom.me;
location ~ /\.well-known/acme-challenge {
allow all;
}
root /var/www/beauteadom.me;
location / {
return 301 https://www.beauteadom.me$request_uri;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
http2_push_preload off;
server_name www.beauteadom.me;
root /var/www/beauteadom.me;
error_log /var/log/nginx/beauteadom.me.log notice;
access_log off;
location / {
http2_push_preload off;
add_header X-Content-Type-Options nosniff;
proxy_pass http://beauteadom_me;
}
location /websocket/ {
proxy_pass http://beauteadom_me;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location ~* \.(html|css|js|png|jpg|jpeg|gif|ico|svg|eot|woff|ttf)$ {
expires max;
proxy_pass http://beauteadom_me;
}
location ~ /\. { deny all; }
gzip on;
gzip_vary on;
gzip_min_length 1000;
gzip_comp_level 2;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";
access_log off;
error_log /var/log/nginx/error.log crit;
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
pagespeed on;
pagespeed FetchHttps enable,allow_self_signed;
pagespeed FileCachePath /var/ngx_pagespeed_cache;
pagespeed RewriteLevel OptimizeForBandwidth;
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
add_header "" "";
}
location ~ "^/pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon$" { }
}
here's what i get in my chrome browser console
I think it's definitely one to one nginx security setting given that i do not have this problem locally
I already googling too much please I need your help. thank you in advance

nginx default_site doesn't appear to be working

I've got nginx running in docker as a reverse proxy and have been for some time - and it works wonderfully, short of one little issue I've recently seen crop up.
What I'd like: when a user gets to my nginx server and there isn't a .conf file specified for the URL, either 404/444 or some other HTTP response that drops the connection.
What I'm seeing: when a user navigates to sudomain.url.com and that subdomain isn't specified in any of my *.conf files, nginx uses the first conf file it finds - ignoring the default.conf. Find my details below.
Any other tips/tricks you can provide would be awesome as well!
nginx.conf:
user nginx;
worker_processes 1;
error_log /etc/nginx/log/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /etc/nginx/log/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 70;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
default.conf:
server {
server_name _;
listen 80 default_server;
return 444;
}
server {
server_name _;
listen 443 default_server;
return 444;
}
Example of a conf file (there are maybe a dozen of these):
server {
listen sub.domain.com:80;
server_name sub.domain.com;
return 302 https://sub.domain.com$request_uri;
}
server {
listen sub.domain.com:443;
server_name sub.domain.com;
ssl_certificate /etc/nginx/keys/ssl.pem;
ssl_certificate_key /etc/nginx/keys/ssl.key;
ssl on;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC4-SHA';
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/keys/dhparams.pem;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
location / {
proxy_pass http://10.0.1.4:81;
proxy_buffering off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
I haven't actually tested this but my gut feeling is that your listen directives shouldn't contain a host name. They should contain the IP address of the interface you want to be listening on and the port you want to be listening to. Then for each different port/IP combination you can specify one of them as the default.
Only after resolving which IP address did the request go to and which port was it on, nginx begins to actually process the request. The first step here is to check the Host header, if it finds a matching server block for the value of the host header then that's where it should route. If it doesn't find one then it should route to the default.
If there is no host header being received then, I think, in more recent versions of nginx it will drop the request, however it would previously just handle this by sending to the default server for the IP/port combo.
Below is an nginx.conf which gives me working endpoints for named servers and returns 404 for everything else. Due to HSTS headers you need to hit test.se{1,2,3,4}.home-v.ind.in to see it work or you will just get back a browser error.
user nginx;
worker_processes auto;
error_log stderr notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
keepalive_timeout 300s;
ssl_certificate /etc/pki/nginx/fullchain.pem;
ssl_certificate_key /etc/pki/nginx/privkey.pem;
ssl_dhparam /etc/pki/nginx/dhparams.pem;
ssl_protocols TLSv1.2;
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_prefer_server_ciphers on;
ssl_buffer_size 1400;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/pki/nginx/fullchain.pem;
add_header "Cache-Control" "no-transform";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
resolver 8.8.8.8 8.8.4.4 216.146.35.35 216.146.36.36 valid=60s;
resolver_timeout 2s;
server {
listen 80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name test.se1.home-v.ind.in;
root /usr/share/nginx/html;
location /.well-known { satisfy any; allow all; try_files $uri $uri/ =404; }
location /robots.txt { satisfy any; allow all; add_header Content-Type text/plain; return 200 "User-agent: *\nDisallow: /\n"; }
location / { satisfy any; allow all; add_header Content-Type text/plain; return 200 "Test Site 1"; }
}
server {
listen 443 ssl http2;
server_name test.se2.home-v.ind.in;
root /usr/share/nginx/html;
location /.well-known { satisfy any; allow all; try_files $uri $uri/ =404; }
location /robots.txt { satisfy any; allow all; add_header Content-Type text/plain; return 200 "User-agent: *\nDisallow: /\n"; }
location / { satisfy any; allow all; add_header Content-Type text/plain; return 200 "Test Site 2"; }
}
server {
listen 443 ssl http2 default_server;
server_name _;
root /usr/share/nginx/html;
location /.well-known { satisfy any; allow all; try_files $uri $uri/ =404; }
location / { return 404; }
}
}

Enable Cors on node.js app with nginx proxy

I have set up a digital ocean droplet that is a reverse proxy server using nginx and node. I used this tutorial from digital ocean as a starting point
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04.
I have also set up ssl with lets encrypt. The issue I am currently having is that I am unable to make cross domain ajax calls to the server. I am getting a error of No 'Access-Control-Allow-Origin' header is present. I have set up the appropriate header response in my node app and have attempted to follow the few examples I could find for nginx with no luck. Below is my code.
nginx with my attempts at headers removed
server {
listen 443 ssl;
server_name lefthookservices.com www.lefthookservices.com;
ssl_certificate /etc/letsencrypt/live/lefthookservices.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/lefthookservices.com/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-$
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security max-age=15768000;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ /.well-known {
allow all;
}
}
server {
listen 80;
server_name lefthookservices.com www.lefthookservices.com;
return 301 https://$host$request_uri;
}
Here is my app.js script using express
'use strict';
var colors = require('colors/safe');
var express = require('express');
var knack = require('./knack_call.js');
var bodyParser = require('body-parser');
var cors = require('cors');
colors.setTheme({
custom: ['blue', 'bgWhite']
});
var app = express();
app.use(bodyParser.json());
// allow for cross domain ajax
app.get('/', function(request, response){
response.send('hello\n');
});
app.post('/', function(request, response){
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
response.header("Access-Control-Allow-Methods', 'GET,POST");
knack.getData(request, response);
});
app.listen(8080, '127.0.0.1', function(m){
console.log(colors.custom("Captin the server is at full strength"));
});
Any suggestion that could help me set the correct headers to allow CORS would be greatly appreciated. Thank you in advance.
As a result of Tristans answer below my Nginx code now looks like this.
server {
listen 443 ssl;
server_name lefthookservices.com www.lefthookservices.com;
ssl_certificate /etc/letsencrypt/live/lefthookservices.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/lefthookservices.com/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES$
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security max-age=15768000;
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if ($http_origin ~*(https?://.*\exponential.singularityu\.org(:[0-9]+)?$)){
set $cors "1";
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}o";
}
if ($cors = "1") {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Credentials: true';
proxy_pass http://127.0.0.1:8080;
}
if ($cors = "1o") {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept';
add_header Content-Length 0;
add_header Content-Type text/plain;
return 204;
}
proxy_pass http://127.0.0.1:8080;
}
}
location ~ /.well-known {
allow all;
}
}
Sadly this is still not working.
server {
listen 80;
server_name lefthookservices.com www.lefthookservices.com;
return 301 https://$host$request_uri;
}
It turns out the error message I was getting was inaccurate. The issue was not header setting. It turned out that I needed to make the request with jsonp and I needed to handle the incoming data differently. An error in the function called by app.js was erroring and causing the connection to time out. This resulted in the appropriate headers not being returned to the browser which caused the error message.
For anyone hoping to find an NGINX config that worked this is mine.
proxy_pass http://127.0.0.1:8080;
# proxy_http_version 1.1;
proxy_set_header Access-Control-Allow-Origin *;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection '';
proxy_set_header Host $host;
# proxy_cache_bypass $http_upgrade;
Thanks you for the suggestions.
Pull Nginx out of this equation. It doesn't have anything to do with your CORs problem if your setup is as similar to mine as I believe it is. I see that you're using the cors module, but you're not actually using it that I can see.
Your settings are simply enough that you might be able to get away with the defaults so, right below app.use(bodyParser.json());, update your app.js with:
app.use(cors());
That might work right out of the box. If it doesn't, you can pass a set of options. Mine looks something like this:
app.use(cors({
origin: myorigin.tld,
allowedHeaders: [ 'Accept-Version', 'Authorization', 'Credentials', 'Content-Type' ]
}));
Other config options are available in the docs.
You're almost there.
You have to think of the proxy as an external server as well as your Node.js application.
So, in short, you need to add a header to your nginx configuration.
Take a look at this link,
https://gist.github.com/pauloricardomg/7084524
In case this ever gets deleted:
#
# Acts as a nginx HTTPS proxy server
# enabling CORS only to domains matched by regex
# /https?://.*\.mckinsey\.com(:[0-9]+)?)/
#
# Based on:
# * http://blog.themillhousegroup.com/2013/05/nginx-as-cors-enabled-https-proxy.html
# * http://enable-cors.org/server_nginx.html
#
server {
listen 443 default_server ssl;
server_name localhost;
# Fake certs - fine for development purposes :-)
ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
ssl_session_timeout 5m;
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Nginx doesn't support nested If statements, so we
# concatenate compound conditions on the $cors variable
# and process later
# If request comes from allowed subdomain
# (*.mckinsey.com) then we enable CORS
if ($http_origin ~* (https?://.*\.mckinsey\.com(:[0-9]+)?$)) {
set $cors "1";
}
# OPTIONS indicates a CORS pre-flight request
if ($request_method = 'OPTIONS') {
set $cors "${cors}o";
}
# Append CORS headers to any request from
# allowed CORS domain, except OPTIONS
if ($cors = "1") {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Credentials: true';
proxy_pass http://serverIP:serverPort;
}
# OPTIONS (pre-flight) request from allowed
# CORS domain. return response directly
if ($cors = "1o") {
more_set_headers 'Access-Control-Allow-Origin: $http_origin';
more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE';
more_set_headers 'Access-Control-Allow-Credentials: true';
more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept';
add_header Content-Length 0;
add_header Content-Type text/plain;
return 204;
}
# Requests from non-allowed CORS domains
proxy_pass http://serverIP:serverPort;
}
}

Nginx set ssl for URLs

Good day. I got nginx server and it runs https connections.
For now all URLs run with https. All i need is - to exclude some URLs from https, so they could be accessed with simple http.
Here is my NGINX config file:
server {
listen 80;
server_name my-fin.ru www.my-fin.ru;
root /usr/server/finance/abacus/webapp;
location ~ ^/.+\.(eot|ttf|woff)$ {
expires max;
add_header Cache-Control public;
add_header Access-Control-Allow-Origin *;
}
location ~ ^/.+\.(ico|jpg|jpeg|gif|pdf|jar|png|js|css|txt|epf|svg)$ {
expires max;
add_header Cache-Control public;
}
location / {
return 301 https://my-fin.ru;
}
}
server {
listen *:443;
server_name my-fin.ru;
client_max_body_size 10m;
gzip on;
gzip_min_length 500;
gzip_buffers 4 8k;
gzip_types text/plain text/xml application/xml application/x-javascript text/javascript text/css text/json application/json;
access_log /var/log/nginx/finance.access.log;
error_log /var/log/nginx/finance.error.log;
ssl on;
ssl_certificate /usr/server/myfin.crt;
ssl_certificate_key /usr/server/myfin.key;
charset utf-8;
root /usr/server/finance/abacus/webapp;
location ~ ^/.+\.(eot|ttf|woff)$ {
expires max;
add_header Cache-Control public;
add_header Access-Control-Allow-Origin *;
}
location ~ ^/.+\.(ico|jpg|jpeg|gif|pdf|jar|png|js|css|txt|epf|svg)$ {
expires max;
add_header Cache-Control public;
}
location / {
# give site more time to respond
proxy_read_timeout 120;
proxy_pass http://127.0.0.1:8087;
proxy_redirect http:// $scheme://;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr ;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
}
}
Please help to configure nginx.
According to this comment, Here's how i would do it.
## non https server
server {
#non ssl server
listen 80;
server_name example.com;
root /path/to/root;
location /features {
#handle /features
}
location /info {
# handle /info
}
location /help {
#handle /help
}
location /
return 301 https://example.com$request_uri;
}
}
## https server
server {
# handle ssl
listen 443 ssl;
server_name example.com subdomain1.example.com;
root /path/to/root;
location ~ /(features|help|info) {
# redirect those 3 subfolders to http
return 301 http://example.com$request_uri;
}
location / {
#handle ssl requests;
}
}
## https subdomain
server {
listen 443 ssl;
server_name subdomain2.example.com;
root /path/to/root;
location ~ /(features|help|info) {
# redirect those 3 subfolders to http
return 301 http://example.com$request_uri;
}
location / {
# subdomain handling
}
}
Please note that https wont work on subdomains unless you have a wildcard SSL certificate, otherwise the browser will issue a warning.

Resources