将NGINX用作Heroku上express.js 404的代理

时间:2019-06-04 17:47:31

标签: node.js nginx heroku

我正尝试将一个新站点部署到使用Express.js和解耦CMS的Heroku。一切正常,问题在于,作为从旧站点迁移的一部分,我需要执行大约300个唯一重定向。

我的想法是,我可以使用NGINX作为代理并将重定向放在其中,但我无法使配置正常工作。

我的应用程序上有NGINX构建包和node js构建包。 这是我的NGINX配置

daemon off;

worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;

events {
    use epoll;
    accept_mutex on;
    worker_connections 1024;
}

http {
    # Buffers
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 2 1k;

    # Timeouts
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 15;
    send_timeout 10;

    # Gzip
    gzip on;
    gzip_comp_level 2;
    gzip_min_length 1000;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain application/x-javascript text/xml text/css application/xml;

    # Logging
    log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
    access_log off;
    error_log logs/nginx/error.log;

    # Other
    server_tokens off;
    include mime.types;
    sendfile on;

    server {
        listen <%= ENV["PORT"] %>;
        server_name _;
        rewrite ^old-path$ https://www.newdomain.com/new-path permanent;
    root /client/public;

        location = / {
            proxy_pass http://127.0.0.1:3001;
            proxy_redirect default;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
        }
    }
}

这是我的package.json文件

{
  "name": "my aoo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "8.10.0",
    "npm": "5.6.0"
  },
  "scripts": {
    "start": "node index.js",
    "server": "nodemon index.js",
    "client": "cd client/ && npm run prod:compress",
    "dev": "concurrently \"npm run client\" \"npm run server\""
  },
  "repository": {
    "type": "git",
    "url": "#########"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "homepage": "##########",
  "dependencies": {
    "babel-register": "^6.26.0",
    "body-parser": "^1.18.3",
    "compression": "^1.7.3",
    "concurrently": "^4.0.1",
    "connect": "^3.6.6",
    "dotenv": "^6.1.0",
    "express": "^4.16.4",
    "express-static-gzip": "^1.1.3",
    "http": "^0.0.0",
    "nodemailer": "^4.6.8",
    "nodemailer-smtp-transport": "^2.7.4",
    "nodemon": "^1.18.4",
    "prerender-node": "^3.2.1",
    "prismic-dom": "^2.1.0",
    "prismic-javascript": "^2.0.1",
    "react-cookie-consent": "^1.9.0",
    "react-router-sitemap-builder": "^1.1.1",
    "serve-static": "^1.13.2",
    "sitemap-generator": "^8.3.1",
    "swig": "^1.4.2"
  }
}

这是Procfile

web: bin/start-nginx npm start

在开发人员中进行测试时,它会执行重定向,并且在根域上访问站点时,它可以工作,但是如果我尝试直接访问路由之外的路径,则会得到404。

谢谢。

1 个答案:

答案 0 :(得分:0)

这是因为React是一个单页面应用程序,因此您必须保持重定向回到index.html文件。添加此命令。

location {
    ...
    try_files $uri /index.html;
}