[英]How to always redirect to index.html in Nginx Docker?
我正在使用 Docker 的nginx:1.16.0-alpine
圖像作為服務反應應用程序(之前構建的),並且我想在任何情況下都重定向到index.html
頁面(在獲取的 URL 中)
nginx.conf
文件有以下內容:
user nginx; worker_processes auto;
error_log /var/log/nginx/error.log warn; pid
/var/run/nginx.pid;
events {
worker_connections 1024; }
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
server {
location / {
try_files $uri $uri/ /index.html;
}
location ~ ^/$ {
rewrite ^.*$ /index.html last;
}
}
}
實際上添加了server
部分,其他行是默認的!
Dockerfile
內容也如下:
FROM nginx:1.16.0-alpine
COPY ./build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
為了確保,在從鏡像構建容器並進入其中的 shell 之后,文件/etc/nginx/nginx.conf
具有上述內容。
但問題是:當我瀏覽 url http://localhost:3000/login (例如)時,它不會重定向到http://localhost:3000/index.html 。 表明:
404 未找到 nginx/1.16.0
(Docker 容器運行在輸出端口 3000 和本地端口 80)
有誰知道為什么它不起作用!?
(我也搜索過類似的方法,但沒有成功!)
更新:
頁面React-router 和 nginx沒有解決問題。
注釋以下行
# include /etc/nginx/conf.d/*.conf;
為什么? 由於線路
include /etc/nginx/conf.d/*.conf;
加載 default.conf 並忽略您的服務器配置。
此外,您需要在服務器中包含根信息(以前由 default.conf 提供)
將以下2個文件放在同一個文件夾中並執行
docker build -t test . && docker run --rm -p 8080:80 test
文件
FROM nginx:1.16.0-alpine
# COPY ./build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
配置文件
user nginx; worker_processes auto;
error_log /var/log/nginx/error.log warn; pid
/var/run/nginx.pid;
events { worker_connections 1024; }
http { include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
#include /etc/nginx/conf.d/*.conf;
server {
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location ~ ^/$ {
rewrite ^.*$ /index.html last;
}
listen 80;
server_name localhost;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.