我已经在digitalocean上创建了一个基本的Droplet,我给自己找了一个域名。当我想得到/时,我会得到一个很好的“Hello World'响应,但是当我想访问任何其他路由时,例如' / x',我收到Cannot {{request}} /x
错误。我相信我的nginx配置存在问题。我还使用LetsEncrypt设置了HTTPS。下面是Nginx配置和Express代码。
Nginx配置:
# HTTP - redirect all requests to HTTPS:
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://$host$request_uri;
}
# HTTPS - proxy requests on to local Node.js app:
server {
listen 443;
server_name your_domain_name;
ssl on;
# Use certificate and key provided by Let's Encrypt:
ssl_certificate /etc/letsencrypt/live/your_domain_name/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain_name/privkey.pem;
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';
# Pass requests for / to localhost:8080:
location / {
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 http://localhost:8080/;
proxy_ssl_session_reuse off;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
proxy_redirect off;
}
}
这里是index.js文件
var express = require('express')
var app = express()
app.get('/x', function(req, res) {
res.send('x')
})
app.get('/', function (req, res) {
res.send('hello world')
})
app.listen(8080, function() {console.log('App started')})
有什么想法吗?我希望每次添加新路由时都能够在不触及nginx配置的情况下路由请求。
答案 0 :(得分:2)
从proxy_pass
设置中删除尾部斜杠:
proxy_pass http://localhost:8080;
如果指定
proxy_pass
而没有URI,请求URI将以与处理原始请求时客户端发送的格式相同的形式传递给服务器,或者在处理时传递完整的规范化请求URI改变了URI。