Nginx前端后端共用一个域名如何配置

在 Nginx 中配置前端和后端共用一个域名的情况,通常是通过路径或子路径将请求转发到不同的服务。以下是一个示例配置,假设:

前端静态文件在 /var/www/frontend/。
后端 API 服务运行在 http://127.0.0.1:5000。
域名是 example.com,其中:
静态前端通过 example.com 访问。
后端 API 通过 example.com/api/ 访问。

server {
    listen 80;
    server_name example.com;

    # 配置前端静态文件
    location / {
        root /var/www/frontend;
        index index.html;

        # 支持前端 history 模式路由
        try_files $uri $uri/ /index.html;
    }

    # 配置后端 API 路由
    location /api/ {
        proxy_pass http://127.0.0.1:5000;
        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;
    }

    # 配置错误页面(可选)
    error_page 404 /404.html;
    location = /404.html {
        root /var/www/frontend;
    }
}

在前端使用基于路由的单页应用程序(如 React、Vue )时,前端的路由模式通常分为 hash 模式 和 history 模式。在 Nginx 配置前端路由时,需要特别处理 history 模式,因为它依赖于 HTML5 的 pushState 功能,而不带 # 的路径直接被 Nginx 视为文件路径。

try_files 指令的作用就是按顺序检査文件是否存在,返回第一个找到的文件。 $uri 是nginx 提供的变量,指当前请求的 URI,不包括任何参数,当请求静态资源文件的时候,命中 $uri 规则;当请求页面路由的时候,命中 /ndex.html 规则

nginx.conf 配置文件位置及其默认配置

# Intel Chip 系统路径
/usr/local/etc/nginx/nginx.conf

# Apple Silicon 系统路径
/opt/homebrew/etc/nginx/nginx.conf

默认配置

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        # error_page   500 502 503 504  /50x.html;
        #location = /50x.html {
        #    root   html;
        #}

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include servers/*;
}

### 多个前端与单个后端集成的架构设计 在现代软件开发实践中,多个前端应用程序共享同一个后端服务是一种常见的模式。为了确保这种架构的有效性和可维护性,建议采用以下策略: #### 微服务架构下的统一网关层 建立一个API Gateway作为所有客户端请求进入系统的唯一入口点[^1]。这不仅简化了前端调用逻辑,还允许对不同类型的流量实施集中化的安全控制、限流措施以及负载均衡。 对于基于Spring Cloud Alibaba构建的应用程序而言,Nginx或Zuul都可以很好地充当此角色,并支持路由转发至相应的内部微服务实例上处理具体业务需求。 ```java // Nginx配置片段示例 server { listen 80; server_name api.example.com; location /service-a/ { proxy_pass http://backend-service-A/; } location /service-b/ { proxy_pass http://backend-service-B/; } } ``` #### 前端应用的身份验证与授权机制 考虑到多前端场景下用户认证的一致性问题,在设计方案时应引入OAuth2.0/OpenID Connect协议来管理访问令牌(Token),并通过JWT(JSON Web Token)形式传递给各个前端应用以便后续资源服务器进行权限校验。 这样做的好处是可以让不同的前端界面共用一套登录状态管理系统,减少重复劳动的同时提高了安全性。 #### 数据交互格式标准化 定义一组RESTful API接口供所有的前端消费,这些接口应当遵循一致的设计原则,比如使用HTTP动词表示操作类型(GET, POST, PUT, DELETE等), 返回JSON结构化数据响应体等等[^2]。 此外还可以考虑利用GraphQL替代传统的REST风格查询语句,它能更灵活地满足复杂的数据获取要求并降低网络传输开销。 #### 跨域资源共享(CORS) 当存在跨源请求的情况时(即前后端部署于不同域名之下),需要适当调整CORS设置以允许合法来源发起AJAX请求。通常是在后端代码里指定允许哪些Host能够读取特定路径上的资源。 ```javascript // Express.js 中间件配置 CORS 支持 const cors = require('cors'); app.use(cors({ origin: ['http://frontend-app-one.com', 'https://frontend-app-two.net'], })); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值