Change .htaccess with PHP

I have a .htaccess that maps a domain to a folder.

RewriteEngine On RewriteBase / # redirect mapped domain ReWriteCond %{HTTP_HOST} joshblease.uk.to ReWriteCond %{REQUEST_URI} !gme-index/ ReWriteRule ^(.*)$ gme-index/$1 [L] 

Is there a way to edit / add additional files to a file using PHP?

I just want to get the contents of the .htaccess file and add to them using a PHP script.

+6
source share
3 answers

As stated in one of the comments above, it is better to use RewriteMap for your case here, and not try to edit .htaccess from PHP code directly. Here is an example of how to use it:

  • Add the following line to the httpd.conf file:

     RewriteMap domainMap txt://path/to/domain-dir.txt 
  • Create a text file as /path/to/domain-dir.txt as follows:

     sub1 /subdir1 sub2 /foodir2 foo /bar 
  • Add this line to the .htaccess file:

     Options +FollowSymLinks -MultiViews RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC] RewriteRule ^$ ${domainMap:%1} [L,R] 

Effectively all of this means that these redirects are in place:

  • sub1.domain.com/ => sub1.domain.com/subdir1
  • sub2.domain.com/ => sub2.domain.com/foodir2
  • foo.domain.com/ => foo.domain.com/bar

Advantage:. With this setting, you can edit or recreate the /path/to/domain-dir.txt file as much as you want from your php code without opening a huge security hole, allowing you to edit php code. htaccess directly.

+3
source

This might work for your situation:

Modify .htaccess to see the following:

 RewriteEngine On RewriteBase / # redirect mapped domain ReWriteCond %{HTTP_HOST} joshblease.uk.to ReWriteCond %{REQUEST_URI} !gme-index/ ReWriteRule ^(.*)$ gme-index/$1 [L] ###CUSTOM RULES### 

PHP script, assuming $ rules contains new changed rules,

 $htaccess = file_get_contents('/path/to/.htaccess'); $htaccess = str_replace('###CUSTOM RULES###', $rules."\n###CUSTOM RULES###", $htaccess); file_put_contents('/path/to/.htaccess', $htaccess); 

the example above is a theory and has not been tested, depends on .htaccess and script access rights.

+3
source

You can use the following htaccess to map any domain other than maindomain.com to a folder with the same name as the domain name.

 RewriteCond %{ENV:REDIRECT_STATUS} ^$ ReWriteCond %{HTTP_HOST} !maindomain.com ReWriteCond %{HTTP_HOST} (.*) ReWriteRule ^(.*)$ %1/$1 [L] 

as an alternative; to map a folder to a domain name without ltd.

 RewriteCond %{ENV:REDIRECT_STATUS} ^$ ReWriteCond %{HTTP_HOST} !maindomain.com ReWriteCond %{HTTP_HOST} ^([^\.]*) ReWriteRule ^(.*)$ %1/$1 [L] 

Not quite what you wanted, but it may work for you and doesn't need php.

+1
source

Source: https://habr.com/ru/post/906225/


All Articles