Search code examples
reactjsamazon-web-servicesamazon-s3urlamazon-cloudfront

remove index.html from URL react app on S3 and CloudFront


I am hosting multiple react apps on one s3 bucket, that is connected to a CloudFront distro. The react apps are placed in folders so for example the calculating app is located in /calculate in the S3 bucket. I fixed issues that happened because react wasn't using paths in a relative way to the index.html (I added "homepage":"./" to the package.json). But I am struggling to remove the index.html from the URL for the end user. Basically I want the index.html to appear when going on https://{domain}/calculate/ not https://{domain}/calculate/index.html . Does someone know how to fix this issue?

Thanks


Solution

  • You can make a file just called ".htaccess" in the root directory and add the following to it:

    RewriteEngine on
    
    # Remove .html (or htm) from visible URL (permanent redirect)
    RewriteCond %{REQUEST_URI} ^/(.+)\.html?$ [nocase]
    RewriteRule ^ /%1 [L,R=301]
    
    # Quietly point back to the HTML file (temporary/undefined redirect):
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^ %{REQUEST_URI}.html [END]