How to replace %PUBLIC_URL% in react app on an azure website
This looks like the index file taken from public
instead of build
.
Like the documentation says, %PUBLIC_URL%
is replaced when you build the project.
Assuming you used create-react-app
, make sure that you're running npm run build
and hosting the files from the build
directory.
HOW TO REPLACE %PUBLIC_URL%
By default, Create React App produces a build assuming your app is hosted at the server root. example.com
If your website isn't served from this root, (maybe you want to serve from example.com/relativepath
, you can override this by specifying the homepage in your package.json
"homepage": "http://example.com/relativepath",
This will let Create React App correctly infer the root path to use in the generated HTML file.
In your case, however, I think you get a 404 error because the Azure is trying to find an index.html (or some other index.* named). To fix this, Azure needs to know how to pass the intended route to the one and only index.html placed at the site's root. Create a new file named web.config
inside /site/wwwroot
folder with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
This will tell Azure to rewrite all urls as if they are pointing to our root file and our SPA application can handle the links correctly.
References:
https://facebook.github.io/create-react-app/docs/deployment#building-for-relative-paths
https://medium.com/@to_pe/deploying-create-react-app-on-microsoft-azure-c0f6686a4321
I hope this may help you