代码之家  ›  专栏  ›  技术社区  ›  BTSM

如何使用.htaccess在同一域中部署两个build-react应用程序

  •  0
  • BTSM  · 技术社区  · 3 年前

    我有两个构建的vite-react应用程序。

    我将在同一域中部署这些。

    例如,如果请求URL为“https://example.com/admin/*“我应该显示app1,对于其他URL,我应该显示app2。

    所以我这样配置.htaccess文件。

    <IfModule mod_rewrite.c>
        Options -MultiViews
        RewriteEngine On
        # For URIs starting with /admin, load the app in admin directory
        RewriteCond %{REQUEST_URI} ^/admin [NC]
        RewriteRule ^(.*)$ /admin/index.html [L]
    
        # For all other URIs, load the app in html directory
        RewriteCond %{REQUEST_URI} !^/admin [NC]
        RewriteRule ^(.*)$ /index.html [L]
    </IfModule>
    

    我使用的是nginx和nginx配置文件是这样的。

            root /var/www;
            location / {
                try_files $uri.html $uri $uri/ /html/index.html;
             }
    

    app1在 /var/www/html/admin 目录,并且app2在 var/www/html 目录

    但我的404错误 /admin/* URL。

    如何解决此问题。

    0 回复  |  直到 3 年前
        1
  •  2
  •   Sagar Vadnere    3 年前

    要修复访问以/admin/*开头的URL时遇到的404错误,您需要调整 Nginx配置 。以下是应能解决此问题的更新配置:

    root /var/www;
    
    location /admin {
        alias /var/www/html/admin;
        try_files $uri $uri/ /admin/index.html;
    }
    
    location / {
        try_files $uri $uri.html $uri/ /index.html;
    }
    

    在更新的配置中:

    • 这个 /管理员 位置块处理以/admin开头的URL请求。它使用alias指令为位于/var/www/html/admin中的app1指定正确的目录路径。try_files指令用于检查请求的URI是否以文件或目录的形式存在。如果没有,它将服务/admin/index.html,这是app1的入口点。

    • 这个 / 位置块处理对所有其他URL的请求。try_files指令检查请求的URI是否以文件的形式存在,并在其后面附加.html,是否作为目录,或者是否为/index.html服务,后者是app2的入口点。

    通过如上所示更新Nginx配置,您应该能够根据URL路径将请求正确路由到相应的应用程序。

        2
  •  2
  •   academic_failure    3 年前

    在nginx中使用htaccess通常不是一个好主意(请参阅 here :“你不能这样做。你不应该。如果你需要。htaccess,你可能做错了。”)。 您可以通过添加以下内容轻松获得所需结果:

    root /path/to/your/root/directory;
    
    location /admin/ {
        alias /path/to/app1/build/;
        try_files $uri $uri/ /index.html;
    }
    
    location / {
        alias /path/to/app2/build/;
        try_files $uri $uri/ /index.html;
    }
    

    到您的nginx配置文件。您也可以使用 htaccess to nginx converter 如果你有任何其他的htaccess规则,你想移植到nginx。

        3
  •  1
  •   BTSM    3 年前

    我这样解决了这个问题。

    我这样编辑nginx配置文件。

          location /admin/ {
                   alias /var/www/html/admin/;
                   try_files $uri.html $uri $uri/ /admin/index.html;
           }
    
            location / {
                root /var/www/html/;
                try_files $uri.html $uri $uri/ /index.html;
             }
    

    当我构建admin react应用程序时,我用这个命令添加了基本的suburl。

    vite build --base=/admin/
    
    推荐文章