使用 nginx 在同一台服务器上托管静态网站和 api 服务 [英] Host static website and api service on same server using nginx
问题描述
我想使用 static 网站 和 API 服务
提供服务>nginx.
I want to serve my static website
and API service
from same machine using nginx.
网站位于 /var/www/html
API 服务在端口 8000
http://localhost
应该打开静态网站http://localhost/api
应该代理运行在端口 8000
http://localhost
should open static website
http://localhost/api
should proxy api service which is running on port 8000
借助 http://nginx.org/en/docs/beginners_guide.html 我试过这个配置
With the help of http://nginx.org/en/docs/beginners_guide.html I tried this config
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location /api {
proxy_pass http://localhost:8000;
}
}
http://localhost
工作正常,但 http://localhost/api
给我错误 404
.
http://localhost
is working fine but http://localhost/api
is giving me error 404
.
实现这样的基础设施应该进行哪些正确的配置?
What should be correct configuration to achive such infrastucture?
推荐答案
这里我正在编写一个配置文件,可以按照您的喜好执行此类操作
Here I am writing a conf that can perform this type of opertaion as you prefer
server {
listen 80;
server_name <server_name_you_prefers>;
location / {
alias /var/www/html/; # Static directory's complete path from root
}
location /api {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_pass_request_headers on;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET,PUT,PATCH,POST,DELETE,OPTIONS,HEAD';
add_header 'Access-Control-Expose-Headers' 'Origin,Content-Length,Content-Range,Authorization,Content-Type';
add_header 'Access-Control-Allow-Headers' 'Content-Length,Content-Range,Authorization,Content-Type,x-json-response';
add_header 'Access-Control-Allow-Credentials' 'true' always;
}
}
这篇关于使用 nginx 在同一台服务器上托管静态网站和 api 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!