Регулярная маршрутизация nginx - PullRequest
0 голосов
/ 19 июня 2019

В настоящее время я пытаюсь получить приложение на основе угловой версии 8.x с маршрутизацией для работы на моем сервере разработки.Я настроил сервер, который предоставляет API-интерфейс для корневого маршрута, а также угловое приложение, которое должно работать по другому маршруту.Ниже приведен минимальный пример nginx-config:

server {
  listen 443 ssl;
  listen [::]:443;

  root /home/user/;
  server_name sub.tld.com;

  ssl_certificate /path...;
  ssl_certificate_key /path...;

  location / {
    proxy_pass http://localhost:10020/;
  }

  location ^~/dashboard {
    alias /home/user/my-dashboard;
    try_files $uri $uri/ /index.html;
    index index.html;
  }
}

Поскольку выражения местоположения, начинающиеся с регулярного выражения, имеют приоритет при выполнении, я ожидал, что он будет работать с обычным вызовом try_files $uri $uri/ /index.html;, который работает для углового приложения.находится в расположении /.

Обычно маршрутизация работает, однако перезагрузка страницы приводит к ошибке, которая приводит к невозможности найти файл /index.html.

Есть кто-нибудь тамопыт работы с таким конвейером развертывания и какие-либо значимые предложения?

1 Ответ

0 голосов
/ 19 июня 2019

Вы должны настроить местоположение , чтобы позволить angular определять маршруты, также это решит проблему перезагрузки.

location / {
      root   /usr/share/nginx/html;
      index  index.html;
      expires -1;
      add_header Pragma "no-cache";
      add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";


      # Old deafult, I comment this because i have SPA app look: line 55
      # try_files $uri$args $uri$args/ $uri $uri/ =404; 

      # If the route dont exist return index.html 
      # This is the best option for (SPA Applications) like: React, Angular 5, Vue.js and Angular.js
      try_files $uri /index.html; 
    }

Вы можете взглянуть на мой файл nginx.conf, где у меня есть флеш-сервер для API и NGINX, который обслуживает угловые файлы dist.

Также вы можете проверить мой репозиторий, где я показываю рабочий пример использования (NGINX, Angular 5, Docker, Flask)

https://github.com/George35mk/Docker-NGINX-NG5-Flask-Elastic

nginx.conf

# ==============================================================================
# New Config
# ==============================================================================

user  nginx;
worker_processes  1;

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;

  keepalive_timeout  65;

  gzip  on;

  # Configuration for the server
  server {

    listen 80;

    location /api {
      proxy_pass http://flask_api:5000;
    }

    location / {
      root   /usr/share/nginx/html;
      index  index.html;
      expires -1;
      add_header Pragma "no-cache";
      add_header Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";


      # Old deafult, I comment this because i have SPA app look: line 55
      # try_files $uri$args $uri$args/ $uri $uri/ =404; 

      # If the route dont exist return index.html 
      # This is the best option for (SPA Applications) like: React, Angular 5, Vue.js and Angular.js
      try_files $uri /index.html; 
    }

  }

}
...