Nginx + nodejs, socket.io for https dosnt work - node.js

I have a problem with customizing my nodejs app on the server (https, socket.io).
I using: pm2, nginx(works on port :3000), nodejs
Prev I customized nginx for :80 port(http) - works fine!.
But when I inserted ssl certificate and customized him I get errors in the console:
"Access to XMLHttpRequest at 'https://example:2053/socket.io/?EIO=3&transport=polling&t=NAPoEIt' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My nginx settings:
server {
listen 80 default_server;
server_name example.com www.example.com;
return 301 http://skinsgaben.com$request_uri;
}
server {
listen 443 ssl;
server_name site.com www.example.com;
ssl_certificate /var/www/site/ssl/example.crt;
ssl_certificate_key /var/www/site/ssl/example.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:3000/;
proxy_redirect off;
# Socket.IO Support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /socket.io/ {
proxy_pass http://localhost:3000/;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
error_log /var/www/site-log/error.log;
access_log /var/www/site-log/access.log;
}

I'm mostly using this pattern for local and remote nodejs apps.
let host = process.env.host || 'your host';
let PORT = process.env.port || 'your port';
let protocol = 'http';
let options = {};
if (APP_ENV === 'production') {
protocol = 'https';
options = {
key: fs.readFileSync(SSL.KEY),
cert: fs.readFileSync(SSL.CERT)
};
}
const server = require(protocol).createServer(options, app);
server.listen({ host, port: PORT }, () => {
console.log(`Server listening on `);
});

Related

How do i enable auth_basic on nginx for a domain and multiple subdomains with only one password?

I successfully added the auth_basic directive to my server block with the following config:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=proxy_cache_path_global:10m loader_threshold=300 loader_files=200 max_size=2g inactive=60m use_temp_path=off;
upstream backend {
server localhost:8080;
keepalive 128;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.com www.example.com app.example.com;
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
proxy_pass http://backend;
proxy_cache_methods GET HEAD;
proxy_cache proxy_cache_path_global;
proxy_cache_key $host$request_uri$cookie_user$slice_range;
proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
proxy_cache_min_uses 3;
proxy_cache_valid any 1m;
proxy_cache_revalidate on;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_cache_lock_age 10s;
proxy_cache_lock_timeout 3s;
proxy_redirect off;
proxy_http_version 1.1;
proxy_read_timeout 300;
proxy_connect_timeout 300;
slice 1m;
add_header X-Cache-Status $upstream_cache_status;
proxy_set_header Host $host;
proxy_set_header Connection "";
proxy_set_header Range $slice_range;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
}
When i visit my website, 2 login prompts appear after each other; one for example.com, and another one for app.example.com.
How do i configure this, so that i only have to type in my credentials once?
I already tried looking for a solution by myself unsuccessfully. Any hints would be appreciated.

nextjs axios requests inside getServerSideProps always return 404 after deployment with nginx

I have nextjs app running on ec2 instance with nodejs backend
When the app makes an axios request inside useEffect it works perfectly, but when the app sends a request from inside getServersideProps function it fails with 404 status code and the request does not arrive to backend at all.
This is the nginx file
server {
server_name frontend.domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
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-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
# we need to remove this 404 handling
# because of Next's error handling and _next folder
# try_files $uri $uri/ =404;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/frontend.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/frontend.com/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 {
server_name api.domain.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://localhost:8080;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/frontend.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/frontend.com/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
}
This is the axios configuration:
const configModified = {
baseURL: 'https://api.domain.com',
withCredentials: true,
headers:{},
adapter: cache.adapter
// global customizations
}
export const request = (request) => {
const source = axios.CancelToken.source();
return {
request: axios({ ...configModified, ...request}, cancelToken: source.token }),
source
}
}
it is working on localhost as expected but after deployment the requests fails only in getServerSideProps function
You have to modify your axios instance based on you are on the server or client.
export default ({ req }) => {
if (typeof window === "undefined") {
// We are on the server
return axios.create({
baseURL:
"http://ingress-nginx-controller.ingress-nginx.svc.cluster.local",
headers: req.headers,
});
} else {
// We must be on the browser
return axios.create({
baseUrl: "https://api.domain.com",
// if it causes error
// baseUrl: "/"
});
}
};
then when you are on server, pass the context object
export const getServerSideProps = async (context) => {
const client = buildClient(context);
...
};

Socket.io with Nodejs not working with nginx reverse proxy

I have a Nodejs server app with Express and Socket.io (Ubuntu 18.04). It always worked fine until nGinx (1.14) reverse proxy entered the scene. The nginx server is running on a different machine of Node.js apps, each app on it's own vm, inside the same network.
Server and Client on version 2.1.1.
The nginx server is responsible for multiple app redirects.
I tried several configuration combinations but nothing works.
Here what I've tried (examples for "company1"):
default.conf in /etc/nginx/conf.d
location /company1-srv/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_redirect off;
proxy_pass http://172.16.0.25:51001/;
}
Then in the client code I connect using "path" options because socket.io misplace it's library path.
// companySrv and URL is actually returned by another service (following code is for illustrative purposes):
let companyUrl = 'https://api.myserver.com/company1-srv';
let companySrv = '/company1-srv';
socket(companyUrl, {
path: companySrv + '/socket.io/'
});
I also tried to remove the path option and configured a specific /location for the socket.io stuff (for testing purposes):
location /socket.io/ {
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;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_redirect off;
proxy_pass http://172.16.0.25:51001/socket.io/;
}
Nothing worked.
It connects, but does'n emits anything. And after a short while (a minute or so), it becomes unavailable, raising the "disconnect" (reason: transport close) client event.
Server:
const io = require('socket.io')(https || http, {
transports: ['polling', 'websocket'],
allowUpgrades: true,
pingInterval: 60000*60*24,
pingTimeout: 60000*60*24
});
I also tried to edit the nginx.conf and write the "upstream socket_nodes { ..." and use the proxy_pass http://socket_nodes. It didn't make sense as I need a exact redirect depending on the company, but for the sake of tests I did, but it doesn't work as well.
What I need to do?
Thanks
We as well use socket.io with reverse-proxy from ngnix. I can share a little bit of our setup, maybe it helps to rule things out.
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
}
stream {
log_format basic '$time_iso8601 $remote_addr '
'$protocol $status $bytes_sent $bytes_received '
'$session_time $upstream_addr '
'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
access_log /var/log/nginx/stream.log basic;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
##
# Server Blocks
##
# DOMAINEXAMPLE A
server {
server_name exampleA.domain.com;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://192.168.21.105:5050;
}
}
# DOMAINEXAMPLE B
server {
server_name exampleB.domain.com;
location /api {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://192.168.21.106:5050;
}
}
}
The most interesting part here are probably the server blocks
# DOMAINEXAMPLE A
server {
server_name exampleA.domain.com;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://192.168.21.105:5050;
}
}
# DOMAINEXAMPLE B
server {
server_name exampleB.domain.com;
location /api {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://192.168.21.106:5050;
}
}
Domain Example A
For location / at http://192.168.21.105:5050 we have a NodeJS process running, including the setup for socket.io
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server);
Domain Example B
For location /api at http://192.168.21.106:5050 we have another NodeJS process running, including a slightly different setup for socket.io
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server, {path: '/api/socket.io'});
In both cases socket.io works perfectly fine for us
Connecting from Client (Example B)
What we actually do on the server side here is creating a namespace for socket.io, like
const io= require('socket.io')(server, {path: '/api/socket.io'});
const nsp = io.of('/api/frontend');
and then on the client side , connect to it like
import io from 'socket.io-client'
const socket = io('https://exampleB.domain.com/api/frontend', {path: "/api/socket.io"});

connect() failed (111: Connection refused) while connecting upstream

[error] 7697#7697: *100335 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: v4.domain.com, request: "GET /socket.io/?__sails_io_sdk_version=0.13.8&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=Luvcibs HTTP/1.1", upstream: "http://127.0.0.1:1338/socket.io/?__sails_io_sdk_version=0.13.8&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=Luvcibs", host: "v4.domain.com", referrer: "http://v4.domain.com/?ct=t(Flash_Sals_Videotoolz_copy_05_12_29_2016)&mc_cid=404a630ab2&mc_eid=c44f7937fe"
[error] 7700#7700: *101735 connect() failed (111: Connection refused) while connecting to upstream, client: XX.XX.XX.XX, server: v4.domain.com, request: "GET /socket.io/?__sails_io_sdk_version=0.13.8&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=LuvciVy HTTP/1.1", upstream: "http://127.0.0.1:1338/socket.io/?__sails_io_sdk_version=0.13.8&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=LuvciVy", host: "v4.domain.com", referrer: "http://v4.domain.com/"
Recently i have configured my sails js application on Ubuntu 16.04 VPS Server which have nginx as reverse server. below is my nginx conf for site
Site runs fine but all of a sudden site break and shows 502 bad gateway.
Tried almost everything whatever i can.
Please help me to get it sorted.
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
#
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/html/php;
# Add index.php to the list if you are using PHP
index index.html index.php index.htm index.nginx-debian.html;
server_name domain.com www.domain.com;
ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot
ssl_dhparam /etc/ssl/certs/dhparam.pem;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
#try_files $uri $uri/ =404;
#try_files $uri $uri/ /index.php?q=$uri&$args;
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files not-existing-file #php;
}
location #php {
#fastcgi_pass 127.0.0.1:9000;
fastcgi_read_timeout 300;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
include snippets/fastcgi-php.conf;
}
location ~* \.(css|js|png|jpg|jpeg|gif|ico)$ {
expires 1d;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
upstream sails_server {
server 127.0.0.1:1338; # fail_timeout=0;
# keepalive 64;
}
server {
listen 80;
listen [::]:80;
server_name v4.domain.com;
root /root/domain/;
#Logging
error_log /root/domain/log/error.log notice;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 300;
proxy_pass http://sails_server;
proxy_redirect off;
# proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection "";
# proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-NginX-Proxy true;
# proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10ms;
# proxy_cache one;
# proxy_cache_key sfs$request_uri$scheme;
# proxy_pass_request_headers on;
}
location /socket.io/ {
proxy_pass http://sails_server/socket.io/;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Port $server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Nginx-Proxy true;
proxy_pass_request_headers on;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_buffers 8 32k;
proxy_buffer_size 64k;
}
}
My PM2 config file for my sails application is below
{
"apps": [
{
"name": "dj",
"script" : "./app.js",
"watch": false,
"ignore_watch" : ["node_modules", ".tmp"],
"watch_options": {
"followSymlinks": false
},
"env" : {
"PORT": 1338,
"NODE_ENV": "production"
}
}
]
}

asp.net core on linux with nginx routing doesn't work

I've created an ASP.NET Core MVC application and deployed it into Linux server. When I go to sitename.com browser shows up the Home/Index page without any problem.
But when I try to go sitename.com/Home/Index or another controller like sitename.com/Admin/Login nginx throws a 404 Not Found error. What should be the problem?
Here is my Startup.cs/Configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Here is my website config from sites-available folder
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /var/www/sitename.com;
index index.html index.htm;
server_name sitename.com www.sitename.com;
location / {
try_files $uri $uri/ =404;
proxy_pass http://127.0.0.1:5000;
}
and nginx.conf
user www-data;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
mail {
}
Remove try_files $uri $uri/ =404; as it's testing if a certain url exists on the file system and if not return 404.
But /Home/Index is a route, which do not map to an existing file but to controller action, hence you get the 404 error.
To help someone searching on Google
I was getting 404, but I realized that ASP Net only accepts 1 server by name
Example NOT POSSIBLE:
server{
listen 80;
listen [::]:80;
server_name example.com;
location /asp_app_ONE {
proxy_pass http://0.0.0.0:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /asp_app_TWO{
proxy_pass http://0.0.0.0:3002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Example OK:
server{
listen 80;
listen [::]:80;
server_name appONE.example.com;
location / {
proxy_pass http://0.0.0.0:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server{
listen 80;
listen [::]:80;
server_name appTWO.example.com;
location / {
proxy_pass http://0.0.0.0:3002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

Resources