如何正确配置nginx以显示SPA应用程序?

时间:2019-09-13 05:44:23

标签: nginx server devops nginx-config

我正在设置一个新服务器,我想使用Nginx部署用Angular编写的应用程序。 Nginx配置应该是什么样子?

这是新的VPS OVH服务器。我已经在该服务器上安装了Nginx,然后在进入“ my-app.com”时尝试将Nginx配置为甚至显示静态index.html。不幸的是,我总是收到“此页面无法访问”的错误消息。

我要在那里传递我的配置:

nginx-conf:


user root;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid   /var/run/nginx.pid;

events {

}

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;

    include /etc/nginx/conf.d/*.conf;


}

然后我在conf.d中获得了2个其他配置:

default.conf

server {
    listen         [::]:80;
    server_name    my-api.com www.my-api.com;
    root           /var/www/html;
    index          index.html;
    try_files $uri  $uri/ /index.html;
}

好的,最后一个:

my-app.com.conf

server {
    listen      [::]:80;
    server_name    my-api.com www.my-api.com;
    root           /var/www/html;
    index          index.html;
    try_files $uri /index.html;
}

在命令之后: nginx -T(测试还可以),然后通过“ sudo service nginx stop”命令停止Nginx并再次启动它。进入浏览器并通过链接“ my-app.com”后,错误仍然存​​在。我的预期结果只是到此页面“ my-app.com”并查看我的应用程序。甚至是静态HTML-也会告诉我我做的是正确的。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的两个其他配置相同,您只需要其中一个即可。也就是说,您已经为NGINX配置了server_name my-api.com www.my-api.com;。这意味着仅当您的请求URI为my-api.comwww.my-api.com时,NGINX才会尝试使用此配置。您可以删除server_name行,以使NGINX对其接收的每个URL使用此配置。 (例如http://{serverip}/http://{domain}/

您正在使用的域(我假设它实际上不是my-api.com)可能未配置到您的Web服务器。 您的域应具有指向您的werbserver的外部IP地址的A记录,并且您的Web服务器的防火墙应具有打开的80端口TCP。

另外,您有listen [::]:80;,我不确定100%,但是我认为这暗示了ipv6的用法。尝试仅使用listen 80;

尝试检查您域的DNS设置,以确保它们正确无误,然后将您的配置更改为

server {
    listen      80;
    root           /var/www/html;
    index          index.html;
    try_files $uri /index.html;
}

确保在服务器的/var/www/html文件夹中具有Angular应用程序的内部版本。