nginx proxy_pass保留应用的位置

时间:2017-08-25 14:23:38

标签: docker nginx

我想使用nginx服务器作为许多使用Docker镜像的Web应用程序的代理。 到目前为止,我能够根据特定路径将请求重定向到应用程序。 以下代码显示了default.conf文件的内容。

upstream app1 {
  server app1:80;
}

upstream app2 {
  server app2:80;
}

server {
  listen       8080;
  server_name  localhost;

  location /app1/ {
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://app1/;
  }

  location /app2/ {
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://app2/;
  }

  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
  root /usr/share/nginx/html;
  }
}

当我加载其中一个应用的网页时,链接在网址中没有应用路径。 例如,它显示http://localhost:8080/somelink而不是http://localhost:8080/app1/somelink。 浏览器的地址栏显示正确的URL(http://localhost:8080/app1/)。 当我单击链接时,Web浏览器会跟随错误的URL。 是否有任何解决方案来指示nginx服务器在URL中保留应用程序路径?

编辑:使用Wordpress重现的示例

以下代码显示如何使用Wordpress Docker镜像重现此行为。问题似乎相同,当我访问http://localhost:8080/wordpress1时,它会重定向到http://localhost:8080/wp-admin/install.php而不是http://localhost:8080/wordpress1/wp-admin/install.php

docker-compose.yml

version: '3'

services:
  proxy:
    image: nginx
    ports:
      - 8080:8080
    restart: always
    volumes:
      - ./default.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - wordpress1
      - wordpress2

  db1:
    image: mysql:5.7
    volumes:
      - db1_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: somewordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

  wordpress1:
    depends_on:
      - db1
    image: wordpress:latest
    restart: always
    environment:
      WORDPRESS_DB_HOST: db1:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress

  db2:
    image: mysql:5.7
    volumes:
      - db2_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: somewordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

  wordpress2:
    depends_on:
      - db2
    image: wordpress:latest
    restart: always
    environment:
      WORDPRESS_DB_HOST: db2:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress

volumes:
  db1_data: {}
  db2_data: {}

default.conf

upstream wordpress1 {
  server wordpress1:80;
}

upstream wordpress2 {
  server wordpress2:80;
}

server {
  listen       8080;
  server_name  localhost;

  location /wordpress1/ {
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://wordpress1/;
  }

  location /wordpress2/ {
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://wordpress2/;
  }

  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
  root /usr/share/nginx/html;
  }
}

0 个答案:

没有答案