Edit .htaccess with PHP

孤街浪徒 提交于 2019-11-26 16:56:05

问题


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 any way to edit/add extra domain maps to the file using PHP?

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


回答1:


As suggested in one of the comments above it is better to use RewriteMap for your case here rather than trying to edit .htaccess from PHP code directly. Here is a sample how to use it:

  1. Add following line to your httpd.conf file:

    RewriteMap domainMap txt://path/to/domain-dir.txt
    
  2. Create a text file as /path/to/domain-dir.txt like this:

    sub1 /subdir1
    sub2 /foodir2
    foo /bar
    
  3. Add these line in your .htaccess file:

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

Effectively all this means is to have these redirects 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 setup in place, you can edit or recreate the file /path/to/domain-dir.txt as much as you want from your php code without opening a huge security hole be allowing php code o edit .htaccess directly.




回答2:


This could work for your situation:

Ammend the .htaccess to look 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 holds the new generated rules to be ammended;

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

example above is theory and has not been tested, would be dependant upon .htaccess privledges and permissions of the script.




回答3:


You could use the following htaccess to map any domain other than maindomain.com to a folder that has the same name as the domain-name.

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

alternatively; to map the folder to the domainname without the ltd.

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

Not exactly what you wanted, but it might work for you, and doesn't need any php.



来源:https://stackoverflow.com/questions/8899805/edit-htaccess-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!