I'm trying to pass through all the directories in my app through to express, and in some cases directories that contain a dynamic 'key' which I'll :capture.
I can't get even a defined sub-directory, /pretest, to pass through to express. Despite copying the the same options for Location /, it serves me an Ngxin 404
Ideally, I want domain.com/prepop/{lookup_key} to pass to localhost:8080/prepop/{lookup_key}
Where {lookup_key} is a different value each time
Any ideas what I'm doing wrong here? Any/all help is much appreciated.
Code-
server.js
const path = require('path');
const express = require("express");
const mysql = require('mysql2');
const cors = require("cors")
const port = process.env.PORT || 8080;
const app = express();
app.use(cors())
app.get('/', (req, res) => {
res.send('hello');
});
app.get('/pretest', (req, res) => {
res.send('test');
});
app.get('/prepop/:lookup_key', (req, res) => {
let connection = mysql.createConnection({
//commented out for stackoverflow
});
connection.connect();
connection.query('SELECT * FROM table_incoming_leads WHERE leadid = '+req.params.send_key, (err, response, fields) => {
if (err) console.log(err);
res.json({
email: response[0].email,
first_name: response[0].first_name,
last_name: response[0].last_name
})
});
connection.end();
})
app.listen(port, () => console.log(`Server listening on port ${port}`));
/etc/nginx/sites-available/default
server {
root /var/www/html;
location / {
proxy_pass http://localhost: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;
try_files $uri $uri/ =404;
}
location /pretest {
proxy_pass http://localhost: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;
try_files $uri $uri/ =404;
}
location /prepop {
proxy_pass http://localhost: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;
try_files $uri $uri/ =404;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/subdomain.mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/subdomain.mydomain.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 {
if ($host = subdomain.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name subdomain.mydomain.com;
return 404; # managed by Certbot
}
You need to remove try_files directive from /prepop location because when nginx receives a request for let's say /prepop/somekey it looks for a file with that name (somekey) in your root directory. Since there is no such file it returns 404.
Related
I am having the issue with my websocket. It works well locally on my computer, but when I run with my nginx server on chrome, I get the error
Do i have to configure my nodejs server with my ssl key? Here's what I have so far:
const app = express()
const httpServer = http.createServer(app)
const io = require('socket.io')(httpServer, {
cors: {
origin: '*',
methods: ['GET, POST'],
credentials: true,
allowedHeaders: ['custom-header'],
},
})
I got my ssl from godaddy, and it contains 3 files. How can i do this?
NGINX SERVER
server {
listen 80;
server_name mydomain + .com;
rewrite ^/(.*) https://mydomain + .com/$1 permanent;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name mydomain + .com;
ssl_certificate /home/chained.crt;
ssl_certificate_key /home/mykey.key;
// React Setup
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_cache_bypass $http_upgrade;
}
// NODEJS SETUP
location /api {
proxy_pass http://localhost:8000;
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;
}
// SOCKET.IO SETUP
location /socket.io/ {
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 false;
proxy_pass http://localhost:8000;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
This is where I set up the REACT SOCKET.IO CODE
useEffect(() => {
if (!socket.current) {
socket.current = io(process.env.REACT_APP_API)
console.log('SOCKET', socket.current)
}
if (socket.current) {
socket.current.emit('join', { userId: user._id })
socket.current.on('connectedUsers', ({ users }) => {
users.length > 0 &&
dispatch({
type: 'SET_CONNECTED_USERS',
payload: users,
})
// users.length > 0 && setConnectedUsers(users)
})
}
When I run my application on chrome, I get the error. Websocket doesn't work, but it works locally.
this is my nginx server setup. I have 2 server instances. I don't know if that is the problem. Anyone knows the best way to fix this??
server {
listen 80;
server_name mydomain + .com;
rewrite ^/(.*) https://mydomain + .com/$1 permanent;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name mydomain + .com;
ssl_certificate /home/chained.crt;
ssl_certificate_key /home/mykey.key;
// Frontend Setup
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_cache_bypass $http_upgrade;
}
// API SETUP
location /api {
proxy_pass http://localhost:8000;
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;
}
// SOCKET.IO SETUP
location /socket.io/ {
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 false;
proxy_pass http://localhost:8000;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
this is my nodejs setup for backend.
const app = express()
const httpServer = https.createServer({}, app)
const io = require('socket.io')(httpServer, {
cors: {
origin: '*',
methods: ['GET, POST'],
credentials: true,
allowedHeaders: ['custom-header'],
},
})
httpServer.listen(port, () => {
console.log(`Server running on port ${port}`)
})
MY react setup looks like this
useEffect(() => {
if (!socket.current) {
socket.current = io(process.env.REACT_APP_API_APP)
console.log('SOCKET', socket.current)
}
if (socket.current) {
socket.current.emit('join', { userId: user._id })
socket.current.on('connectedUsers', ({ users }) => {
users.length > 0 &&
dispatch({
type: 'SET_CONNECTED_USERS',
payload: users,
})
// users.length > 0 && setConnectedUsers(users)
})
}
My application works locally. but on nginx, It doesn't work. I just get the error as shown in the image.
I am new to servers. Any help would be appreciated.
I am trying to set up my node server that uses express to serve files on port 3000 and the net library to serve a TCP server on port 5052, so:
const express = require('express');
const app = express();
const httpServer = require('http').Server(app);
const io = require('socket.io').listen(httpServer);
const path = require('path');
const net = require('net');
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'))
});
let server = net.createServer(function(socket) {
// Left out for brevity
}
server.listen(5052, 'localhost');
httpServer.listen(3000, () => {
console.log('Ready on port 3000');
});
Locally, this all works very well. I can load up localhost:3000 and I get my HTML served and it connects to socket.io fine. I can also connect to the server on port 5052 perfectly and life is good. I just can't get nginx to serve it all correctly. Here's what I have:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name mycoolproject.com www.mycoolproject.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_cache_bypass $http_upgrade;
}
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/mycoolproject.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mycoolproject.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
server {
listen 5053;
server_name mycoolproject.com www.mycoolproject.com;
location /{
proxy_pass http://localhost:5052;
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;
}
}
When I navigate to mycoolproject.com I get the site loaded fine, so the express side is working fine. I just can't connect to my server on 5053. Any ideas?
You need to configure a different port for Nginx, 5052 is busy by Node.js.
server {
listen 5053;
server_name mycoolproject.com www.mycoolproject.com;
location /{
proxy_pass http://localhost:5052;
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;
}
}
Then you can connect to mycoolproject.com:5053
I'm following a book Building Bots with node.js
I have a server with node.js node red and ngnix on line
I clone simple serve code from github
https://github.com/azure-appservice-samples/NodeJS-EmptySiteTemplate
When i tried to proxy in nginx I have this error:
Cannot GET /bottest
this is default directives for ngnix
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
# Default server configuration
#
server {
#listen 80 default_server;
#listen [::]:80 default_server;
#server_name **************;
#return 301 http://$server_name$request_uri;
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name *****************;
# SSL configuration
#
#listen 443 ssl default_server;
#listen [::]:443 ssl default_server;
include snippets/ssl-*************.conf;
include snippets/ssl-params.conf;
# 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;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location ~ /.well-known {
allow all;
}
location /nodered {
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
proxy_pass http://**************:1880;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /hello1 {
proxy_pass ***************:1880;
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 /bottest {
proxy_pass **********:8181;
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 / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
# fastcgi_pass unix:/run/php/php7.0-fpm.sock;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}
this is my server.js code:
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
res.send('This is my Facebook Messenger Bot - Whos Off Bot
Server');
});
// for facebook verification
app.get('/webhook', function (req, res) {
if (req.query['hub.verify_token'] ===
'whosoffbot_verify_token') {
res.status(200).send(req.query['hub.challenge']);
} else {
res.status(403).send('Invalid verify token');
}
});
app.post('/webhook', function (req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
if (event.message.text.indexOf('hi') > -1) {
sendMessageWithInitialOptions(event.sender.id);
}
}
}
res.sendStatus(200);
});
function sendMessageWithInitialOptions(recipientId) {
messageData = {
'attachment': {
'type': 'template',
'payload': {
'template_type': 'button',
'text': 'Pl. Select your options',
'buttons': [{
'type': 'postback',
'title': 'Schedule a Meetting',
'payload': 'SCHEDULE A MEETING'
}, {
'type': 'postback',
'title': 'Whos Off When',
'payload': 'WHOS OFF WHEN',
}, {
'type': 'postback',
'title': 'My Schedule',
'payload': 'MY SCHEDULE'
}]
}
}
};
sendMessage(recipientId, messageData);
};
function sendMessage(recipientId, message) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: 'PAGE_ACCESS_TOKEN' },
method: 'POST',
json: {
recipient: { id: recipientId },
message: message,
}
}, function (error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
};
app.listen((process.env.PORT || 8181));
anyone can help me?
http://www.minvolai.com/blog/2014/08/Setting-up-a-Secure-Single-Node-Elasticsearch-server-behind-Nginx/Setting-up-a-Secure-Single-Node-Elasticsearch-server-behind-Nginx/
server {
listen 80;
server_name http://dev.nodejs.com/;
location / {
rewrite ^/(.*) /$1 break;
proxy_ignore_client_abort on;
proxy_pass http://localhost:3000;
proxy_redirect http://localhost:3000 http://dev.nodejs.com/;
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;
}
}
Please refer this link
I Wonder how can i handle subdomains in my project that based on Expressjs.
Here's My nginx configuration
server {
listen 80;
server_name bee.local;
access_log /var/log/nginx/bee.local.access.log;
error_log /var/log/nginx/bee.local.error.log;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header X-Forwarded-For $remote_addr;
}
}
server {
listen 80;
server_name api.bee.local;
access_log /var/log/nginx/bee.local.access.log;
error_log /var/log/nginx/bee.local.error.log;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header X-Forwarded-For $remote_addr;
}
}
and here's my router with subdomain support
router.get('/v1/', function(req, res, next) {
res.status(200).json({ title: "title" });
});
app.use(subdomain('api', router));
The problem is that it's rendering the index route
and for sure i setuped the hosts file
I've been searching for 3 hrs can you help me :)
There are several requirements:
Setup Host header in nginx with required domain or proxy if applicable
Use subdomain middleware before other middlewares that handle endpoints
Work example:
nginx configuration:
server {
listen 80;
server_name bee.local;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
listen 80;
server_name api.bee.local;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
nginx configuration with hardcoded Host header values:
I believe that you did not setup Host header correctly. please try next configuration
server {
listen 80;
server_name bee.local;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
# proxy_set_header Host $host;
proxy_set_header Host bee.local;
}
}
server {
listen 80;
server_name api.bee.local;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
# proxy_set_header Host $host;
proxy_set_header Host api.bee.local;
}
}
express app:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.get('/', function(req, res) {
res.send('Homepage');
});
app.listen(3000);