Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optimal .htaccess configuration for Angular 9, Angular 8, Angular 7, Angular 6, Angular 5 (and older) app in production incl. fix for the angular browser caching issue.

New generator

I created a new htaccess generator for angular apps that makes it easier for you to create the optimal htaccess file: https://julianpoemp.github.io/ngx-htaccess-generator/

The goal of this generator is to make the configuration process much easier. To make this possible I created a kind of interview mode with some questions. As an additional feature the generator supports adding exclusions for example if you have installed a blog in a subdirectory of your web application.

The generator 😁: https://julianpoemp.github.io/ngx-htaccess-generator/ The project: https://github.com/julianpoemp/ngx-htaccess-generator Place for issues and bug reports: https://github.com/julianpoemp/ngx-htaccess-generator/issues

New updates will be implemented in the generator only.


Optimal htaccess file for angular apps (old)

Angular supports two different routing strategies:

If you are using PathLocationStrategy you have to append a .htaccess file to your production server in order to make routing work. For more information about Angular's routing click here.

What is the problem? (old)

If you are using PathLocationStrategy and you are not using a .htaccess file reloading your angular app does not work. For example: Imagine your app navigated to the URL https://example.com/page1/page2 where your app is located on https://example.com/. If you now try to reload your app, it won't work because the webserver does not find the path /page1/page2/ because the path is generated by Angular.

Installation (old)

  1. Place the .htaccess file (below this instruction) next to your app's index.html on your web server.
  2. If your app is on the root of your domain like https://example.com you don't have to do more steps.
  3. If your app is not on the root of domain like https://example.com/app/ you have to set the base-href attribute correctly: Call ng build --base-href /app/ to build your app. Replace /app/ with the path from the root of your domain.

Redirection to https (old)

If you need redirection to https just uncomment the two lines of the REDIRECTION part.

Disable Browser caching (old)

In cases where you are loading custom files (e.g. from the assets folder) that are loaded via XHR request you need to disable browser caching. If you do not disable it your custom assets are cached by the browser and changes are not activated on the user's browser.

To disable browser caching just uncomment the BROWSER CACHINGpart.

Troubleshooting

If you are facing any issues try to answer the following questions. It helps to solve the most problems. If not, post a comment to this gist with the answers to these questions.

  1. Does your routing work using ng serve locally? If no, then your routing settings are wrong.
  2. Does your web-server support htaccess files? Some web hoster like gitlab-pages does not support htaccess files.
  3. Is the .htaccess file placed next to your index.html file?
  4. Is your app installed in the root of your domain or in a subfolder?
  5. What is your base-href value? If your app is located in a subfolder like https://example.com/awesome/ your base-ref attribute must be /awesome/. If that's not the case, the default value is /.

Contributors

Information

Version 1.4.0, last updated on 2020-01-08

Other helpful scripts

There are other scripts I'm using in my Angular projects:

# For instructions and new versions of this Gist go to:
# https://gist.github.com/julianpoemp/bcf277cb56d2420cc53ec630a04a3566
# Version 1.4.1
<IfModule mod_rewrite.c>
RewriteEngine On
# -- REDIRECTION to https (optional):
# If you need this, uncomment the next two commands
# RewriteCond %{HTTPS} !on
# RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
# --
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]
</IfModule>
#------------ BROWSER CACHING (optional)
# Disable browser caching for all files that don't get a hash string by Angular.
#<FilesMatch "^(?!.*\.([0-9a-z]{20})\.).*$">
# <IfModule mod_headers.c>
# FileETag None
# Header unset ETag
# Header unset Pragma
# Header unset Cache-Control
# Header unset Last-Modified
# Header set Pragma "no-cache"
# Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
# Header set Expires "Mon, 10 Apr 1972 00:00:00 GMT"
# </IfModule>
#</FilesMatch>
#------------
@divyatiwari5

This comment has been minimized.

Copy link

@divyatiwari5 divyatiwari5 commented Apr 21, 2018

Thanks a lot!

@patriciovergaratobar

This comment has been minimized.

Copy link

@patriciovergaratobar patriciovergaratobar commented Nov 8, 2018

thank you! 👍

@RogierVC

This comment has been minimized.

Copy link

@RogierVC RogierVC commented Jan 4, 2019

Thank you for this but background images defined in CSS will not load if your Angular app is not on the root of the domain :)

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Jan 21, 2019

Thank you for this but background images defined in CSS will not load if your Angular app is not on the root of the domain :)

Yes you are right. If that's the case you need to replace the index.html line with that:

RewriteRule ^(.*) /directory_path/index.html [NC,L]

The directory_path part is a relative part to the host. For example, if the host is http://example_domain.com than the URL the htaccess will direct to is http://example_domain.com/directory_path/index.html.

@ensiente

This comment has been minimized.

Copy link

@ensiente ensiente commented Mar 24, 2019

Thank you! Very useful gist

@utsahpaikraySteg

This comment has been minimized.

Copy link

@utsahpaikraySteg utsahpaikraySteg commented May 8, 2019

Thanks

@Mhmad-Alnajjar

This comment has been minimized.

Copy link

@Mhmad-Alnajjar Mhmad-Alnajjar commented Jun 22, 2019

Great thx.

@RaschidJFR

This comment has been minimized.

Copy link

@RaschidJFR RaschidJFR commented Jul 16, 2019

Hi. I've noticed it fails when entering directly from a longer url (for example https://domain.com/app-root-folder/some/deeper/view. So I forked it and did some enhancementes. @julianpoemp Feel free to merge.
Cheers!

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Jul 16, 2019

Hi. I've noticed it fails when entering directly from a longer url (for example https://domain.com/app-root-folder/some/deeper/view. So I forked it and did some enhancementes. @julianpoemp Feel free to merge.
Cheers!

@RaschidJFR, thank you for your enhancements! I was able to test it with one level of directories and it works well. I'm currently not able to test it with more levels, but I beliefe you that it works. I merged your changes and added you to the list of contributors :)

@RaschidJFR

This comment has been minimized.

Copy link

@RaschidJFR RaschidJFR commented Jul 17, 2019

Glad to help bud :)

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Aug 20, 2019

Hi guys, I'm glad that this gist helps you :). If you are looking for more helpful gists, check out my other gists. There you can find the following gists, that are very useful to me:

  • SubscriptionManager as easy and secure way to manage subscriptions
  • easy way using webworkers in angular
  • fixing the underscore problem
  • angular upgrade scripts to easily upgrade to newer versions
  • script to optimize the folder structure of an angular build
@Lavanya2021

This comment has been minimized.

Copy link

@Lavanya2021 Lavanya2021 commented Aug 22, 2019

can anyone suggest for htaccess for main domain and its https

@RaschidJFR

This comment has been minimized.

Copy link

@RaschidJFR RaschidJFR commented Aug 22, 2019

@Lavanya2021 this one work. Just follow the instructions.

@Lavanya2021

This comment has been minimized.

Copy link

@Lavanya2021 Lavanya2021 commented Aug 23, 2019

@Lavanya2021 this one work. Just follow the instructions.

which one..? i have tried the above .htaccess but it doesn't work for me. Please suggest me if there is any other way to rewrite to index.html in https main domains.

Thank you

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Aug 23, 2019

@Lavanya2021 this one work. Just follow the instructions.

which one..? i have tried the above .htaccess but it doesn't work for me. Please suggest me if there is any other way to rewrite to index.html in https main domains.

Thank you

We need more information in order to help you.

Can you explain exactly what is not working?

What's the URL to the index.html?

Do you use option 1 or 2?

Is your base-href attribute correct?

Does your web server allow using .htaccess configurations?

Did you change anything in this .htaccess file?

@Daniyal83

This comment has been minimized.

Copy link

@Daniyal83 Daniyal83 commented Sep 14, 2019

Awesome! Thanks man.

@Daniyal83

This comment has been minimized.

Copy link

@Daniyal83 Daniyal83 commented Sep 14, 2019

By the way how to add and where the redirection to HTTPS? I tried different variations but none of them worked. I'm getting 500 Server error.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Sep 15, 2019

By the way how to add and where the redirection to HTTPS? I tried different variations but none of them worked. I'm getting 500 Server error.

@Daniyal83 The best way would be if you set the redirection to https in your web server. If you just have web space I think you can set this option in your the administration area of your web space.

If you have to set it using the .htaccess file I think you can set this two lines right after the "RewriteEngine On" (line 14):

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Source: https://stackoverflow.com/questions/4083221/how-to-redirect-all-http-requests-to-https

Does it work?

@Daniyal83

This comment has been minimized.

Copy link

@Daniyal83 Daniyal83 commented Sep 17, 2019

No. It didn't work. I tried that solution. The way it worked for me is I placed those lines at the very top of the file, above the # INFORMATION

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Sep 19, 2019

@Daniyal83: I tested it and it only worked for me, if I set the correct base-href attribute. If you redirect to https, but your base-href is neither "/" nor contains "https://" at the beginning, it does not work.

I added a section about redireection to https to the .htaccess file.

@Daniyal83

This comment has been minimized.

Copy link

@Daniyal83 Daniyal83 commented Sep 21, 2019

My code is a little different from what you suggested. (I'm using Beget hosting by the way)

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
@aris-resultstel

This comment has been minimized.

Copy link

@aris-resultstel aris-resultstel commented Oct 2, 2019

how do you handle angular optional parameters?

when i try to use something like /login;page=contactus it seems it will just redirect to /login.. basically the optional parameters seems to be ignored.

Im currently using as shown below.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.html [NC,L]
@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Oct 2, 2019

how do you handle angular optional parameters?

What do you mean with optional parameters? Do you mean GET parameters like /login?param1=value1&param2=value.
Are you sure that ther is not any typo in your example?

In my apps I'm using GET parameters and the .htaccess works very well with them.

@aris-resultstel

This comment has been minimized.

Copy link

@aris-resultstel aris-resultstel commented Oct 3, 2019

to use the angular optional parameters, I've used semicolon (;) like this /login;param1=value1 instead of /login?param1=value1

Reference here for optional parameters: https://www.youtube.com/watch?v=vy0zhvCH-RM

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Oct 5, 2019

to use the angular optional parameters, I've used semicolon (;) like this /login;param1=value1 instead of /login?param1=value1

Reference here for optional parameters: https://www.youtube.com/watch?v=vy0zhvCH-RM

Thanks for the information, I've never heard of that. Because I'm currently not using optional parameters would it be possible for you to test my .htaccess file?

@Achyuthkodali

This comment has been minimized.

Copy link

@Achyuthkodali Achyuthkodali commented Oct 28, 2019

Thanks man, you saved my app in production.

@webmasterashishgaur

This comment has been minimized.

Copy link

@webmasterashishgaur webmasterashishgaur commented Oct 30, 2019

you are a big life saver, I was looking for this from couple of hours, thank you so much for this.

@amjadkhanroot

This comment has been minimized.

Copy link

@amjadkhanroot amjadkhanroot commented Nov 3, 2019

you just saved my day!

@Gennier

This comment has been minimized.

Copy link

@Gennier Gennier commented Dec 9, 2019

Hello guys,
Need help with longer url. For example: (www.example.com/testing) - Works, (www.example.com/testing/testing1) - Doesnt Work.
I read above but don't understand.

The error that I receive is.

  • Uncaught SyntaxError: Unexpected token '<' - for runtime.js
  • Uncaught SyntaxError: Unexpected token '<' - for polyfills.js
  • Uncaught SyntaxError: Unexpected token '<' - for main.js
  • Resource interpreted as Stylesheet but transferred with MIME type text/html:
@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Dec 9, 2019

@Genrier
make sure to add a file named ".htaccess" next to your index.html. Set it's contents with the code above. If this does not work, answer the following questions:

@Gennier

This comment has been minimized.

Copy link

@Gennier Gennier commented Dec 9, 2019

@julianpoemp
Copied it in htaccess
Yeap the .htaccess is in the same folder where index.html is.

  • The vaule of my base-href in index.html is "./". "/" doesnt work.
  • My index.html is (www.example.com/testing/index.html).
  • Yes the path /testing/testing1/ is working on localhost using ng serve

Looking at the source in inspect element, it seems that the error is cause by serving js as html?
there is <!doctype html> in a js file

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Dec 9, 2019

@Gennier
I think it should work if you set your base-href to "/testing/". You can see the base-href attribute as absolute path from the host to your index.html.

@Signulator

This comment has been minimized.

Copy link

@Signulator Signulator commented Dec 9, 2019

Thanks! Works perfectly.

@Gennier

This comment has been minimized.

Copy link

@Gennier Gennier commented Dec 10, 2019

@Gennier
I think it should work if you set your base-href to "/testing/". You can see the base-href attribute as absolute path from the host to your index.html.

@julianpoemp

Sorry it doesnt work. The route would be wrong. It automatically becomes (www.example.com\testing\testing). which of course donst exist.
My folder structure is,

  • html
    • testing
      • .htaccess
      • index.html
@Gennier

This comment has been minimized.

Copy link

@Gennier Gennier commented Dec 10, 2019

@Gennier
I think it should work if you set your base-href to "/testing/". You can see the base-href attribute as absolute path from the host to your index.html.

@julianpoemp

Sorry it doesnt work. The route would be wrong. It automatically becomes (www.example.com\testing\testing). which of course donst exist.
My folder structure is,

  • html

    • testing

      • .htaccess
      • index.html

@julianpoemp
After further investigation, it seems that it is serving index.html file content in runtime.js, polyfills.js, main.js. I think it is due to the rerouting of htaccess.

Any solution for this?

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Dec 10, 2019

@Gennier
try to remove the htaccess file and call your app's URL directly. If this doesn't work, the problem is not located in my htaccess file. My htaccess file is a fix for the reload-issue.

Have a look on the network tab of your browser's developer tools. There you can check what files were not found and what URL was requested.

If it automatically becomes /testing/testing/ try to set your base-href to just "/".

If that doesn't help, I don't know why it's not working for you. It works for me and other people very well. I'm using this htaccess file for apps where it's index.html is in a subfolder, too.

@ACHEER1420

This comment has been minimized.

Copy link

@ACHEER1420 ACHEER1420 commented Dec 28, 2019

I am really confused here,
I try to put Angular be one part of WP website like www.example.com/angular,
but when I directly put URL like www.example.com/angular/product1 it shows 404

I tried to config .htaccess file
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

RewriteRule ^.$ - [NC,L]
RewriteRule ^all-products/
$ all-products/index.html [NC,L]

But so far it doesn't work, please help.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Dec 29, 2019

I am really confused here,
I try to put Angular be one part of WP website like www.example.com/angular,
but when I directly put URL like www.example.com/angular/product1 it shows 404

I tried to config .htaccess file
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

RewriteRule ^.$ - [NC,L] RewriteRule ^all-products/$ all-products/index.html [NC,L]

But so far it doesn't work, please help.

your .htaccess file is incorrect. Just use my .htaccess file and place it next to your app's index.html. Make sure, that your base-href attribute is correct.

For example: Your index.html is available on www.example.com/angular/index.hml, the .htaccess file path must be www.example.com/angular/.htaccess. Your base-href attribute is "/angular/".

Does it work with ng serve? If not, your routing is the problem.

@cagb80

This comment has been minimized.

Copy link

@cagb80 cagb80 commented Dec 30, 2019

Really thanks...!

@ACHEER1420

This comment has been minimized.

Copy link

@ACHEER1420 ACHEER1420 commented Dec 31, 2019

@julianpoemp thank you so much, I put it in the subdirectory and it works.

@pflores86

This comment has been minimized.

Copy link

@pflores86 pflores86 commented Jan 8, 2020

@julianpoemp Please help me, I tried using your htaccess code but I couldn't fix the problem

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Jan 8, 2020

@pflores86

I need more information. Please answer the following questions:

  1. Does your routing work using ng serve locally? If no, then your routing settings are wrong.
  2. Does your web-server support htaccess files? Some web hoster like gitlab-pages does not support htaccess files.
  3. Is the .htaccess file placed next to your index.html file?
  4. Is your app installed in the root of your domain or in a subfolder?
  5. What is your base-href value? If your app is located in a subfolder like https://example.com/awesome/ your base-ref attribute must be /awesome/. If that's not the case, the default value is /.

When you have any more information that helps to reproduce your issue, tell me.

@pflores86

This comment has been minimized.

Copy link

@pflores86 pflores86 commented Jan 8, 2020

@julianpoemp Thanks for answering.
I think I found the problem in my case, the problem is that the hosting doesn't support htaccess (plesk onyx windows) but I'm trying to found the solution for that.

  1. Does your routing work using ng serve locally? If no, then your routing settings are wrong. Yes, it works
    2. Does your web-server support htaccess files? Some web hoster like gitlab-pages does not support htaccess files. Possible problem
  2. Is the .htaccess file placed next to your index.html file? Yes
  3. Is your app installed in the root of your domain or in a subfolder? It's in a root of a subdomain
  4. What is your base-href value? If your app is located in a subfolder like https://example.com/awesome/ your base-ref attribute must be /awesome/. If that's not the case, the default value is /. It's ok
@guillefd

This comment has been minimized.

Copy link

@guillefd guillefd commented Jan 20, 2020

👍

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Jan 22, 2020

@Obliczeniowo

  1. Does your routing work using ng serve locally? If no, then your routing settings are wrong.
  2. Does your web-server support htaccess files? Some web-hoster like gitlab-pages does not support htaccess files.
  3. Is the .htaccess file placed next to your index.html file?
  4. Is your app installed in the root of your domain or in a subfolder?
  5. What is your base-href value? If your app is located in a subfolder like https://example.com/awesome/ your base-ref attribute must be /awesome/. If that's not the case, the default value is /.

My apps make use of subdirectories in URL, too. Something like https://www.example.com/drawing/drawnig/ works for me with this .htaccess file.

@Obliczeniowo

This comment has been minimized.

Copy link

@Obliczeniowo Obliczeniowo commented Jan 22, 2020

I solved my problem I add whole htaccess from code that was added by author above and now It's work perfectly. My base href is /

@rssaranece94

This comment has been minimized.

Copy link

@rssaranece94 rssaranece94 commented Jan 23, 2020

Thanks a lot. Works beautifully..

@idenisysinc

This comment has been minimized.

Copy link

@idenisysinc idenisysinc commented Feb 18, 2020

I have an angular project in base location https://example.com and I have a subfolder for Wordpress blog ie. https://example.com/blog
redirecting to /blog often gives 404 error.

@ojathelonius

This comment has been minimized.

Copy link

@ojathelonius ojathelonius commented Feb 25, 2020

Hint for Windows users : do not use Git Bash to build your app if you use the --base-href attribute as it's bugged, and will use the absolute path instead of the relative one.

Use PowerShell or cmd instead.

@seifooriamin

This comment has been minimized.

Copy link

@seifooriamin seifooriamin commented Apr 2, 2020

Hi,
Thank you for sharing your .htaccess file. I have a problem with excluding my API folder.
my .htaccess file is as shown below but I want to exclude my API folder that make some troubles for me with some modules.

`
RewriteEngine On
RewriteCond %{HTTP_HOST} ^app.mydomain.com [NC]
RewriteRule ^(.*)$ http://www.app.mydomain.com/$1 [L,R=301]

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html
`

Also I was using your .htaccess file but the same issue happens, having said that my API folder path is http://www.app.mydomain.com/api

Thank in advance for your help

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Apr 2, 2020

Hi @seifooriamin,

at the moment the .htaccess provided by me does not support exclusions, because it will always direct to your app's index.html. Does the following code work for you? Please let me know if that works, I would like to update my htaccess file than and add an explanation.


# For instructions and new versions of this Gist go to:
# https://gist.github.com/julianpoemp/bcf277cb56d2420cc53ec630a04a3566
# Version 1.4.0

<IfModule mod_rewrite.c>
	RewriteEngine On

 	# -- REDIRECTION to https (optional):
	# If you need this, uncomment the next two commands
	# RewriteCond %{HTTPS} !on
  	# RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
	# --

        RewriteRule ^api/*$ %{REQUEST_URI} [L,R=301]

	RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
	RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

	RewriteRule ^.*$ - [NC,L]
	RewriteRule ^(.*) index.html [NC,L]
</IfModule>

#------------ BROWSER CACHING (optional)
# Disable browser caching in production. You can add/remove file extension as you wish.
#<FilesMatch "\.(html|htm|js|json|css)$">
#	<IfModule mod_headers.c>
#		FileETag None
#		Header unset ETag
#		Header unset Pragma
#		Header unset Cache-Control
#		Header unset Last-Modified
#		Header set Pragma "no-cache"
#		Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
#		Header set Expires "Mon, 10 Apr 1972 00:00:00 GMT"
#	</IfModule>
#</FilesMatch>
#------------
@seifooriamin

This comment has been minimized.

Copy link

@seifooriamin seifooriamin commented Apr 3, 2020

@julianpoemp
Thank you for your help and prompt reply, actually I realized that the issue is something else, but I have not find the logic of that.
First I added your update and found that the problem persists. Than I revert my .htaccess and realized that all the APIs module are working perfectly except two of them. Both are related to User Password update. I was wondering that all the modules which are related to other parts of the API are working smoothly, but for these two APIs, the page redirected to index.html event with your .htaccess.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Apr 3, 2020

@seifooriamin I thought about it and found an error in my code posted before:

I assume your API is a REST API? In that case your commands look something like .../api/user/create a.s.o. The code posted by me would redirect only if it's just .../api/. That's why I would change it to this code:

# For instructions and new versions of this Gist go to:
# https://gist.github.com/julianpoemp/bcf277cb56d2420cc53ec630a04a3566
# Version 1.4.0

<IfModule mod_rewrite.c>
	RewriteEngine On

 	# -- REDIRECTION to https (optional):
	# If you need this, uncomment the next two commands
	# RewriteCond %{HTTPS} !on
  	# RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
	# --

        RewriteRule ^api/?(.*) %{REQUEST_URI} [L,R=301]

	RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
	RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

	RewriteRule ^.*$ - [NC,L]
	RewriteRule ^(.*) index.html [NC,L]
</IfModule>

#------------ BROWSER CACHING (optional)
# Disable browser caching in production. You can add/remove file extension as you wish.
#<FilesMatch "\.(html|htm|js|json|css)$">
#	<IfModule mod_headers.c>
#		FileETag None
#		Header unset ETag
#		Header unset Pragma
#		Header unset Cache-Control
#		Header unset Last-Modified
#		Header set Pragma "no-cache"
#		Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
#		Header set Expires "Mon, 10 Apr 1972 00:00:00 GMT"
#	</IfModule>
#</FilesMatch>
#------------

If that still does not work, I recommend you to use an htaccess tester like https://htaccess.madewithlove.be/ in order to debug this problem.

@seifooriamin

This comment has been minimized.

Copy link

@seifooriamin seifooriamin commented Apr 3, 2020

Dear @julianpoemp, Thank you so much for your follow up.
Yes, my API is REST API and surprisingly the issue was the name of API file, in both files the name was containing "password" for instance password_update.php, I have tried several .htaccess as well as yours, but the issue persisted. Also I was wondering, because the rest of modules were working perfectly. for test purpose I change the name of those file, then I realized that the issue solved without excluding API folder .
By the way thank you for your cooperation.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Apr 5, 2020

Hi guys,

thank you so much for your positive feedback! Because there are some situations that need individual configurations I decided to create a generator for .htaccess files. The goal of this generator is to make the configuration process much easier. To make this possible I created a kind of interview mode with some questions. As an additional feature the generator supports adding exclusions for example if you have installed a blog in a subdirectory of your web application.

The generator 😁: https://julianpoemp.github.io/ngx-htaccess-generator/
The project: https://github.com/julianpoemp/ngx-htaccess-generator
Place for issues and bug reports: https://github.com/julianpoemp/ngx-htaccess-generator/issues

Feel free to contribute! 😄

Cheers,
Julian

@amineVestas

This comment has been minimized.

Copy link

@amineVestas amineVestas commented May 8, 2020

Hi,
Thank you @julianpoemp this is very helpfull,
I'm using Angular 8, I have several modules in my app, your .htaccess is working well when i import modules into my app module, but i have errors when using lazy loading (loadChildren).
The error is not 404, but in the console i have several "Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced"
Thank you for your help

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 8, 2020

Hi @amineVestas,
does it work in your development envirenoment using ng serve? If no, then it's something with your Angular code. If yes, then it's something on the server side. "The server responded with a non-JavaScript MIME type of "text/html"- did you look on the "network" tab of your browser's web tools? What's the response of the failed request? Is your baseHref attribute correct?

@amineVestas

This comment has been minimized.

Copy link

@amineVestas amineVestas commented May 8, 2020

Hi @julianpoemp,
Thank you for your time, i forgot to empty path in my module router, now it's working fine.

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

Hi @julianpoemp,
I'm using Apache server on AWS . I've made the angular build (ng build --prod ) for my Angular 9 web app. On my server I'm using path as
/var/www/html/getithomenow/public_html where my build contents are placed.I'm getting the same issue of reloading (404 error).I've provided the href ="/" in index.html file.
on opening my domain getithomenow.com , https://www.getithomenow.com/home is opening .

Below is my .htaccess file.

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^.*$ - [NC,L]
  RewriteRule ^(.*) index.html [NC,L]

  RewriteCond %{SERVER_PORT} 80
  RewriteRule ^(.*)$ https://www.getithomenow.com/$1 [R,L]
</IfModule>

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 23, 2020

Hi @lovemapa,

When you call https://www.getithomenow.com the server is looking for the index.html which is placed in the root folder where your app build was placed. The reason why you can't access https://www.getithomenow.com/home directly is that the server can't find the directory "home". The ressource for /home is generated by angular. That means that the root of the problem is your htaccess file. The base-href value is correct.

As I can see you did the redirections part and you added a part for redirection to HTTPS. I'm using a similar one and it works very well. Please try to replace the old htaccess file with the following code generated by my htaccess generator:

# Generated with ngx-htaccess-generator v1.0.2
# https://julianpoemp.github.io/ngx-htaccess-generator/

<IfModule mod_rewrite.c>
  RewriteEngine On

  # Redirection to HTTPS:
  RewriteCond %{HTTPS} !on
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
  
  # Redirection of requests to index.html
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^.*$ - [NC,L]
  RewriteRule ^(.*) index.html [NC,L]
</IfModule>
@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

Hi @julianpoemp Sir, DOCUMENT_ROOT is just a variable I guess,right ? It has to be relplaced by by /var/www...... and what about REQUEST_URI ? what should I place this value? Because above didn't work out for me by exactly copying and pasting
Thanks

@AbdelhediIssamIng

This comment has been minimized.

Copy link

@AbdelhediIssamIng AbdelhediIssamIng commented May 23, 2020

hi @lovemapa
j'ai eu ce probleme avec angular 9 aussi et j'ai passé plus que 4 jours afin de le résoudre.
principalement c'est mon htaccess :

-- Options -MultiViews -Indexes   RewriteEngine On   # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]   # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301]   # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.html [L]

puis :

  • Dans app.module.ts ; remplacer 'HashLocationStrategy' par 'PathLocationStrategy' dans la partie providers.

  • ajouter {useHash: true} dans le fichier app-routing

  • utiliser cette commande pour générer un build : ng build --prod --base-href "http://0.0.0/my-app/" (remplacer 0.0.0 par l'adresse du serveur et my app c'est le nom de ton projet ) .
    j'espère que cela vous aidera :)

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 23, 2020

Hi @julianpoemp Sir, DOCUMENT_ROOT is just a variable I guess,right ? It has to be relplaced by by /var/www...... and what about REQUEST_URI ? what should I place this value? Because above didn't work out for me by exactly copying and pasting
Thanks

@lovemapa that are constants from your web server. Your Apache should replace them automatically.

  1. Is your .htaccess placed next to your index.html?
    ...
    |_ index.html
    |_ .htaccess

  2. Can you call the /home URI on your local server? (e.g. http//localhost:4200/home) If not, please check your angular routing.

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

@julianpoemp
Yes i'm able to call http//localhost:4200/home on my local server. On my local server its working fine.

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

@AbdelhediIssamIng I tried your .htaccess, but when trying to open my website ("https://www.getithomenow.com"), getting certification error as i'm redirecting from https to http

@AbdelhediIssamIng

This comment has been minimized.

Copy link

@AbdelhediIssamIng AbdelhediIssamIng commented May 23, 2020

change HTTP to HTTPS in .htaccess and not forget the other steps

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

sorry @AbdelhediIssamIng but getting this error. Mixed Content: The page at 'https://www.getithomenow.com/' was loaded over HTTPS, but requested an insecure script 'http://13.58.150.33/getithomenow.com/public_html/main-es2015.d5b51ebe221aa81ea899.js'. This request has been blocked; the content must be served over HTTPS.

@AbdelhediIssamIng

This comment has been minimized.

Copy link

@AbdelhediIssamIng AbdelhediIssamIng commented May 23, 2020

dont be sorry :)
try to rewrite the .htaccess as it was ( you're code ) and complet the other steps ( specilay the ng build with --basehref)

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 23, 2020

@lovemapa I think it's something with your server configuration because my .htaccess code works with a lot of applications. When I test it on https://htaccess.madewithlove.be/ the requests are redirected to the index.html. It's important to prevent the 404 error.

  1. Is the use of .htaccess files enabled in your server configuration? https://askubuntu.com/questions/429869/is-this-a-correct-way-to-enable-htaccess-in-apache-2-4-7

  2. What is the folder structure of your website? Does the domain www.getithomenow.com reference to /var/www/html/getithomenow/public_html and your app is inside public?

  3. Is the .htaccess file really next to the index.html file of your app?

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

@julianpoemp

1.) yes ,.htaccess is enabled in my server

2.) yes in my config file, DocumentRoot falls to /var/www/html/getithomenow/public_html
infact here is my conf file

<VirtualHost *:80>
ServerAdmin admin@getithomenow.com
ServerName getithomenow.com
ServerAlias www.getithomenow.com
DocumentRoot /var/www/html/getithomenow.com/public_html

ErrorLog /var/www/html/getithomenow.com/logs/error.log
CustomLog /var/www/html/getithomenow.com/logs/access.log combined


<Directory "/var/www/html/getithomenow.com/public_html">
    AllowOverride All
</Directory>

RewriteEngine on
RewriteCond %{SERVER_NAME} =getithomenow.com [OR]
RewriteCond %{SERVER_NAME} =www.getithomenow.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

3.)

Screenshot from 2020-05-24 00-28-38
Here is the ScreenShot where index.html and .htaccess are placed next to each other.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 23, 2020

@lovemapa perhaps the redirect in your conf creates this problem. Can you please disable the following lines and try it again?

RewriteEngine on
RewriteCond %{SERVER_NAME} =getithomenow.com [OR]
RewriteCond %{SERVER_NAME} =www.getithomenow.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

to

#RewriteEngine on
#RewriteCond %{SERVER_NAME} =getithomenow.com [OR]
#RewriteCond %{SERVER_NAME} =www.getithomenow.com
#RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

@julianpoemp , Unfortunately no luck. :(
this is my ssl.-conf
in case it could help in finding error

IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin admin@getithomenow.com
ServerName getithomenow.com
ServerAlias www.getithomenow.com
DocumentRoot /var/www/html/getithomenow.com/public_html

ErrorLog /var/www/html/getithomenow.com/logs/error.log
CustomLog /var/www/html/getithomenow.com/logs/access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /path/to/SSL-KEY
SSLCertificateKeyFile //path/to/Cert
</VirtualHost>
</IfModule>

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 23, 2020

@lovemapa sorry, I'm out of ideas now... I think that's an error in the server config somewhere... perhaps you can find something in the error.log or access.log. The redirection to the index.html does not work.

Please let me know the solution as soon as you found one. It's interesting for me to know the solution, too.

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

@julianpoemp , I'll try my best and get back to you. Thanks fot your time.

@lovemapa

This comment has been minimized.

Copy link

@lovemapa lovemapa commented May 23, 2020

@AbdelhediIssamIng , Sorry I couldn't reply you earlier, and I tried your approach but couldn't solve the problem. Thanks for you time though.

@cjosue15

This comment has been minimized.

Copy link

@cjosue15 cjosue15 commented May 26, 2020

Hello, thanks for your work, I have a question, I have a domain like this https://domain.pe, this is the root directory, here is a website made in wordpress, I have created a subdomain like this https://app.domain.pe and in this I want to deploy my application in angular, my question is if this file also works for subdomains and if so how should I use it? thank you very much I am new to this topic.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 26, 2020

@CJosue yes, it works with subdomains. I recommend to install your Angular app in a directory next to the directory where wordpress is installed. The reason is that the Wordpress installation has its own .htaccess file that can lead to conflicts with the Angular App.
For example:

(the absolute paths are fictional)
/var/www/domain.pe/   <- Wordpress installation, reference to https://domain.pe/
/var/www/app.domain.pe/ <- Angular App, reference to https://app.domain.pe/
@cjosue15

This comment has been minimized.

Copy link

@cjosue15 cjosue15 commented May 26, 2020

@julianpoemp thanks for your answer, I will try to follow your recommendation, so what would be the option that I must activate in the file generator in order for it to work with the subdomain?

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented May 26, 2020

@cjosue15 The generated .htaccess file fixes the redirection issue by default. The other options are optional :). Just download the .htaccess file and place it next to your app's index.html. You don't have to change your base-href attribute because "/" is the default and should work for you.

@cuncon-lonton

This comment has been minimized.

Copy link

@cuncon-lonton cuncon-lonton commented Jul 1, 2020

Thanks!!!

@Engshreen

This comment has been minimized.

Copy link

@Engshreen Engshreen commented Jul 21, 2020

I still have this problem ,
My project inside folder called dist , .htaccess in the same folder beside index.html

this is my htaccess file
`
RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html
# to allow html5 state links
RewriteRule ^(.*) /dist/index.html [NC,L]

`

i don't know what is the problem , i tried all solution provided here but nothing work

@cuncon-lonton

This comment has been minimized.

Copy link

@cuncon-lonton cuncon-lonton commented Jul 21, 2020

@Engshreen
do you have actived rewrite mod on your web server? i use apache httpserver 2.4 and i have to active Module Rewirte on httpd.conf File:

LoadModule rewrite_module modules/mod_rewrite.so

My Understanding i have to activate this Module (My Case: Rewrite Module) to allow web server access to the .htaccess file, In any case, please make sure that your web server can apply the settings in the .htaccess file

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Jul 21, 2020

@Engshreen
I recommend using my .htaccess file because it's tested by a lot of people and should work at first try.
If you want to keep your .htaccess code, I think the error is in the line RewriteRule ^(.*) /dist/index.html [NC,L], because your .htaccess is already next to your index.html and not in a subdirectory called dist. I assume your requests are going to be redirected to http://www.exampledomain.com/dist/dist/index.html, that does not exist. Try changing the line to

RewriteRule ^(.*) index.html [NC,L]

Is your code wrapped by an <IfModule mod_rewrite.c></IfModule>?

@Engshreen

This comment has been minimized.

Copy link

@Engshreen Engshreen commented Jul 21, 2020

@julianpoemp
Now i use your file but i got the same error

@Engshreen

This comment has been minimized.

Copy link

@Engshreen Engshreen commented Jul 21, 2020

@Engshreen
do you have actived rewrite mod on your web server? i use apache httpserver 2.4 and i have to active Module Rewirte on httpd.conf File:

LoadModule rewrite_module modules/mod_rewrite.so

My Understanding i have to activate this Module (My Case: Rewrite Module) to allow web server access to the .htaccess file, In any case, please make sure that your web server can apply the settings in the .htaccess file

i use the same version , please tell me how to activate it

@Engshreen

This comment has been minimized.

Copy link

@Engshreen Engshreen commented Jul 21, 2020

@Engshreen
do you have actived rewrite mod on your web server? i use apache httpserver 2.4 and i have to active Module Rewirte on httpd.conf File:

LoadModule rewrite_module modules/mod_rewrite.so

My Understanding i have to activate this Module (My Case: Rewrite Module) to allow web server access to the .htaccess file, In any case, please make sure that your web server can apply the settings in the .htaccess file

@julianpoemp @cuncon-lonton I did it , thank you very much

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Jul 21, 2020

@Engshreen fantastic! What was the solution? Activating the mod_rewrite?

@Engshreen

This comment has been minimized.

Copy link

@Engshreen Engshreen commented Jul 21, 2020

@Engshreen fantastic! The problem was it the mod_rewrite issue?
mod_rewrite was activated , but the problem was in httpd.conf file , i have to change AllowOverride None to AllowOverride All
in <directory /var/www/html>

@cuncon-lonton

This comment has been minimized.

Copy link

@cuncon-lonton cuncon-lonton commented Jul 22, 2020

@Engshreen @julianpoemp very nice, have a good day guys

@hesptech

This comment has been minimized.

Copy link

@hesptech hesptech commented Jul 29, 2020

thank you, worked as if it was magic!

@rajatmittal

This comment has been minimized.

Copy link

@rajatmittal rajatmittal commented Sep 8, 2020

Thank you for this but background images defined in CSS will not load if your Angular app is not on the root of the domain :)

Yes you are right. If that's the case you need to replace the index.html line with that:

RewriteRule ^(.*) /directory_path/index.html [NC,L]

The directory_path part is a relative part to the host. For example, if the host is http://example_domain.com than the URL the htaccess will direct to is http://example_domain.com/directory_path/index.html.

I have to deploy my angular app in WildFly 10 server, where I have to put .htaccess class or is there any other setting I have to do in server.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Sep 9, 2020

@rajatmittal I don't know Wildfly, I'm sorry. I haven't found any result on Google search about Wildfly and .htaccess. I think you have to do the redirection directly on your server using its configuration files.

@hgsantana

This comment has been minimized.

Copy link

@hgsantana hgsantana commented Sep 11, 2020

Hi!

Thank you so much for this. It solved 90% of my problems.

But I'm having trouble when my clients try to access: http://example.com/etc/etc/.

My app is the root of my domain. Everything else works fine when the user is behind the HTTPS protocol. Trying to access directly through HTTPS://example.com/etc/etc everything works fine, but trying HTTP://example.com/etc/etc it redirects to HTTPS://example.com/index.html then HTTPS://example.com/

Can you help me with that? I'm already using your .htaccess file.

@hgsantana

This comment has been minimized.

Copy link

@hgsantana hgsantana commented Sep 11, 2020

Ok, I've just solved my problem. Maybe you want to update your .htaccess file and your generator too.

Once again, the problem with your file is that when someone need to redirect from HTTP to HTTPS it rewrites the URI back to /index.html. So when we try to go HTTP://example.com/etc it goes to HTTPS://example.com/index.html then to HTTPS://example.com/.

To fix this, I added the [L] flag in the 11th line as follows:
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

Doing this it redirects to HTTPS://example.com/etc just fine. Everything else works fine too.

@julianpoemp

This comment has been minimized.

Copy link
Owner Author

@julianpoemp julianpoemp commented Sep 12, 2020

@hgsanta thank you for your feedback! You're right, I will change it :)

@ashiquzzaman

This comment has been minimized.

Copy link

@ashiquzzaman ashiquzzaman commented Sep 15, 2020

Thanks a lot!!!

@jocafi

This comment has been minimized.

Copy link

@jocafi jocafi commented Oct 12, 2020

Thank you very much, @julianpoemp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.