按路径配置nginx vhost

按路径配置nginx vhost,nginx,nginx-config,nginx-location,Nginx,Nginx Config,Nginx Location,我希望通过路径中的第一项为我的项目提供服务,例如,应该为/usr/share/nginx/html/projectname中的项目提供服务 我的配置是这样的: server { listen 80; server_name example.com www.example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl; listen

我希望通过路径中的第一项为我的项目提供服务,例如,应该为/usr/share/nginx/html/projectname中的项目提供服务

我的配置是这样的:

server {
    listen 80;
    server_name example.com www.example.com;
    rewrite ^/(.*) https://example.com/$1 permanent;
}

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

    ssl_certificate "/etc/ssl/XX.pem";
    ssl_certificate_key "/etc/ssl/XX.key";
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
    server_name  example.com/$1 www.example.com/$1;

    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    location /projectname {
        root   /usr/share/nginx/html/projectname ;
        index  index.html;

        try_files $uri $uri/ /index.html?$args;
    }
}
观察:
当我访问配置的域时,它将路由到nginx defalt页面,而不是显示预期的项目。

1:在Linux机器中打开sudo vi/etc/hosts文件

2:
127.0.0.1 example.com www.example.com

3:保存并退出。

3更改:

  • 不要重写,而是返回301
  • 在第二个服务器块中,在服务器名称的末尾没有
    /$1
  • location/projectname
    块中删除
    index index.html

  • 试试这个,它应该会工作。

    这可能是因为服务器名称中的
    /$1
    。@anemyte在删除了/$1之后它仍然不工作检查所讨论的配置是否真的导入到
    /etc/nginx/nginx.conf
    中,并查看导入了哪些其他配置文件。在
    /etc/nginx/nginx.conf
    中查找
    include
    语句,其中一个语句应该通过glob或直接匹配所讨论的配置文件,例如
    include conf.d/*.conf
    。我仍然看到相同的行为。您在重写regex stmt时是否尝试过
    ^(.*)
    <代码>重写^(.*)https://example.com/$1我进行了编辑,但没有更改您是否也重新加载了?我重新启动了nginx服务我进行了更改,这些更改似乎有效,但现在react项目无法在浏览器中加载。我发现您需要启用JavaScript才能运行此应用程序。但我可以在“源”选项卡中看到记录的项目文件。你有这方面的信息吗!对不起,我不知道。。。如果这个答案有助于回答的NGINX部分,不要忘记对答案进行投票。
    server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://example.com/$request_uri;
    }
    
    server {
        listen       443 ssl;
        listen       [::]:443 ssl;
    
        ssl_certificate "/etc/ssl/XX.pem";
        ssl_certificate_key "/etc/ssl/XX.key";
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
        server_name  example.com www.example.com;
    
        access_log /var/log/nginx/nginx.vhost.access.log;
        error_log /var/log/nginx/nginx.vhost.error.log;
    
        location /projectname {
            root /usr/share/nginx/html/projectname ;
    
            try_files $uri $uri/ /index.html?$args;
        }
    }