How to get Dynamic URL through HTACCESS file in PHP?

1.3k views Asked by At

I need to use dynamic sub domain in the url. My PHP application will open account for users.

My URL for login screen will be

http://example.dev/app/login

After logging in, user will go to the following section

http://example.dev/app/section/account_name=ram

My current domain is example.dev

My requirement is to bring account name in the domain name. My URL should be like the following

http://ram.exmaple.dev/app/section

Similarly, if my account name is sundar means , my URL should be like this

http://sundar.example.dev/app/section

I know this is possible using .HTACCESS. I tried this but I am not able to get it correctly

RewriteCond %{HTTP_HOST} ^([a-z-]+).example.dev$ [NC]

RewriteRule (.*)$ /app/section/?account_name=%1[QSA]

Is the above is correct?

Important Point: At the end of htaccess, I have to call one controller file.

RewriteRule ^(.*)$ example_controller.php

1

There are 1 answers

2
vbence On

I understand you want no cahnge in example_controller.php at all.

PHP accesses the original URL with: $_SERVER["REDIRECT_URL"] it will contain the original request address, not the "last but one" request address.

The only solution I can think of is a reverse proxy. You can use .htaccess to create proxy requests (with the [P] directive) to your own host to the desired URL. This way PHP will see that URL as REDIRECT_URL because that is an original URL of a request.

RewriteCond %{HTTP_HOST} ^([a-z-]+).example.dev$ [NC]
RewriteRule (.*)$ http://example.dev/app/section/?account_name=%1[PQSA]

RewriteRule ^(.*)$ example_controller.php

You have to have mod_proxy enabled of course. I'm not sure how P and QSA directives work togather, give it a try.