本篇文章主要是记录 一次使用 docker成功部署nginx之后,代理(部署)静态资源或前端vue项目,遇到的2个问题(docker安装nginx参考)
1.前置条件,防火墙关闭,开放80端口,docker、nginx一切正常。
挂载关联关系:
宿主机目录与nginx容器内目录对应
/home/nginx/html --> /usr/share/nginx/html
2.前端项目或静态资源,放在宿主机的 /home/nginx/html/目录下
以下问题以test为例
有一个test文件夹,里面有一个 index.html页面。
于是资源路径:/home/nginx/html/test/index.html
第一个问题:访问代理路径,报500,日志如下
[error] 23#23: *2 rewrite or internal redirection cycle while internally redirecting to "/test/index.html", client: 192.168.5.1**, server: localhost, request: "GET /test HTTP/1.1", host: "192.168.0.1**"
解决办法
错误的nginx配置:
root /usr/share/nginx/html; --> 容器内路径
(alias当前配置的是宿主机的路径:alias /home/nginx/html/test;)
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /test {
alias /home/nginx/html/test;
index index.html index.htm;
try_files $uri $uri/ /test/index.html;
}
#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 /usr/share/nginx/html;
}
}
正确的配置:alias /usr/share/nginx/html/test;
尽管资源是放到宿主机的目录,但是配置时,还是得配置 容器内的目录
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /test {
alias /usr/share/nginx/html/test;
index index.html index.htm;
try_files $uri $uri/ /test/index.html;
}
#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 /usr/share/nginx/html;
}
}
第二问题:正确访问报403 forbidden问题
解决办法
修改nginx.conf文件,把user nginx; 改为 user root;
user root;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
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;
}
修改完成之后,重启nginx,访问正常!
docker restart nginx