How to remove the static/index.html from URL while using React's HashRouter?

Viewed 374

I'm using a React frontend with a DRF backend an I've hosted both on the same URL. I get the static production build for the frontend and I've put it under the static folder and when a person goes to the main URL contoso.com they are redirected to contoso.com/static/index.html where the static build is served and the different URLs can be accessed correctly using the HashRouter and reloading the page, etc works as expected but the links are like contoso.com/static/index.html#home, contoso.com/static/index.html#menu, etc. I would like to have under the main URL only as in contoso.com/#home, contoso.com/#menu. The API backend for this exists under contoso.com/api.
Additional info: Hosted on IIS v10 with wfastcgi with static folder as public

2 Answers

Fist change the TEMPLATES code from settings.py like that

'DIRS': [
            os.path.join(BASE_DIR, '/static') #If index.html file is in static folder.
        ],

then in the project.urls.py

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
   #...
    path('', TemplateView.as_view(template_name='index.html')),
]

Now unplug the previous view that you shared in the comment and use this URL to render index.html from the build of React frontend.

Then this will work as you wanted. example.com/#home

Was able to separate out the api (DRF) portion under another path on the base web.config file and then set a default document with the index.html. So I think the best option would be to move this to your production server to take care (IIS in this case)

<handlers>
  <add name="Django FastCGI"
        path="api"
        verb="*"
        requireAccess="Script" />
</handlers>

<staticContent>
    <mimeMap fileExtension=".*" mimeType="text/html" />
</staticContent>

<defaultDocument>
    <files>
        <clear />
        <add value="index.html" />
    </files>
</defaultDocument>
Related