Search code examples
.htaccessurl-rewritingsubdomain

HTACCESS Rewrite to subdomain + rewrite url's


I have a question about my HTACCESS. I've been experimenting with my HTACCESS for a while, and finally got the url rewriting to work - in combination with my own written php router.

I want to rewrite the url's not only to make them appear cleaner but also because i use it for the api. So i can do a GET/POST/PUT/DELETE to api/users and add a new user, update or remove etc.

Now i use these lines for the URL rewrite:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule .*/api/(.*)$ api.php [QSA,L]

for the subdomain rerouting to a folder i use

RewriteCond %{HTTP_HOST} ^demo\.example\.com [NC]
RewriteRule (.*) http://example.com/demo/$1 [L,R=301]

The only problem now is that i can not seem to get these combined. I would like to have a url like:

demo.domain.com/api/user

If i use the two apart from each other they work like expected, but combined the url rewrite for the /api always fails. This is probably due to the rewrite condition of the subdomain, but i can't see how i can combine the two.


Solution

  • I found the solution, also i extended the htacces.. Here is my htaccess file:

    # No Caching for page files
    <filesMatch "\.(html|htm|js|css|php)$">
    <IfModule mod_headers.c>
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires 0
    </IfModule>
    </filesMatch>
    
    # Error pages
    ErrorDocument 404 https://%{HTTP_HOST}/#/404
    ErrorDocument 500 https://%{HTTP_HOST}/#/500
    
    RewriteEngine On
    
    # Rewrite www to non
    RewriteCond %{HTTP_HOST} !=""
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R,L]
    
    # Rewrite http to https
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
    
    # Ignore conditions for files and folders
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    
    RewriteBase /
    
    # Rewrite /api to api.php
    RewriteRule ^api/(.+)$ api/api.php [QSA,L]
    
    # Rewrite /downloads to downloads.php
    # RewriteRule ^download/(.+)$ download/download.php [QSA,L]