【问题标题】:Return 404 for invalid routes via nginx通过 nginx 为无效路由返回 404
【发布时间】:2021-03-24 23:24:56
【问题描述】:

我正在使用带有反应的 nginx。 我的 nginx.conf 文件

server {
listen 80;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
}

根据此配置,nginx 为所有路由提供 200 个服务。 假设我的路线是

  example.com/login
  example.com/landing
  

现在假设有人输入了错误的网址

 example.com/test

在这种情况下,我想抛出 404 而不登陆到 nginx 级别的应用程序本身。这是否可以在 nginx 级别处理路由并发送 404,尽管有 200,而不是在反应级别处理。

我发现要在 nginx 级别限制任何特定路由,我们可以使用以下代码来实现

location ^~ /test/ {
    return 404
}

但我想限制所有对我使用无效的路线

# return 404 for all routes
location / {
    return 404;
}
# define each possible route like this
location /login {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
}

location /landing {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
}

但是在此之后我的应用程序没有加载得到 503 Service Temporarily Unavailable

第一个问题是真的有可能在 nginx 级别实现路由,如果是的话,我需要采取任何线索或参考的方法会有很大帮助。 提前致谢

编辑 请找到docker文件

# Base Image
FROM node:10-alpine AS base
MAINTAINER test@test.com
RUN mkdir -p /usr/src/app
COPY . /usr/src/app

# Dependencies
FROM base as build
WORKDIR "/usr/src/app"
RUN npm install
RUN npm run test
RUN npm run build

# Web Server
FROM nginx:alpine
EXPOSE 80
COPY --from=build /usr/src/app/build /usr/share/nginx/html
COPY --from=build /usr/src/app/nginx.conf /etc/nginx/conf.d/default.conf

【问题讨论】:

  • 能否请您发布您的Dockerfile
  • @SachithMuhandiram 添加了 docker 文件

标签: javascript reactjs docker nginx


【解决方案1】:

是的,nginx可以用来做这个。

COPY --from=build /usr/src/app/nginx.conf /etc/nginx/nginx.conf

就用这个吧。

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2021-02-01
    相关资源
    最近更新 更多