skip to Main Content

the structure of my server is

/build/ (a react application is deployed here) and /api/ (a PHP application is deployed here)

I want to redirect traffic from www.test.com/* to /build
and traffic from www.test.com/api/* to /api

this is the current .htaccess I have

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^(.+.(js|css|svg|png))$ /build/$1 [L]

RewriteRule . /build/index.html [L]

# Rewrite the base route to /build/index.html
RewriteRule ^$ /build/index.html [L]

this rule works for fine for all test cases except the / (root) that one renders the root index file instead of the one under /build/index.html

2

Answers


  1. Chosen as BEST ANSWER
    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^(api)($|/) - [L]
    
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    RewriteRule ^(.+).js$ /build/$1.js [L]
    RewriteRule ^(.+).css$ /build/$1.css [L]
    
    RewriteRule . /build/index.html [L]
    

    this approach seems to be working


  2. Try with this:

    RewriteEngine On
    RewriteBase /
    
    # Rewrite requests to /api/ to the /api directory
    RewriteRule ^api/ /api/$1 [L]
    
    # Rewrite requests for static files to the /build directory
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^build/ - [L]
    
    RewriteRule ^(.+.(js|css|svg|png))$ /build/$1 [L]
    
    # Rewrite everything else to /build/index.html
    RewriteRule ^ /build/index.html [L]
    

    This configuration will redirect requests to /api/ to the /api directory, serve static files from the /build directory, and for all other requests, it will rewrite them to /build/index.html. The modification to the root ^ rule ensures that the root URL serves the correct /build/index.html file.

    edit:

    If you suspect the issue is related to the RewriteRule for the /api/ requests, you can try the following modification to handle these requests:

    RewriteRule ^api/ - [L]
    
    # Serve PHP scripts under /api/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^api/(.*)$ /api/$1 [L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search