使用 PHP 动态添加到 .htaccess 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6358330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:08:04  来源:igfitidea点击:

Use PHP to Dynamically Add To .htaccess File?

php.htaccessmod-rewritednsdynamic

提问by Drew

What I am trying to do is automate the process of going live with websites. These websites are all dynamically created using htaccess, so here is an example:

我想做的是自动化网站上线的过程。这些网站都是使用 htaccess 动态创建的,所以这里是一个例子:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^(.*)$ /folder%{REQUEST_URI}?%{QUERY_STRING} [QSA,L]

What I do is add a domain alias for domain.com, and then point it to my server IP and the htaccess file makes it view what is in the /folder.

我所做的是为domain.com添加域别名,然后将其指向我的服务器 IP,htaccess 文件使其查看 / 文件夹中的内容。

It works fine but we are planning to have hundreds of websites and adding that snippet of code to the htaccess manually can get pretty annoying. Since all I am changing is domain.comand the /folder, is there a way to use PHP to dynamically add to the bottom of the .htaccess file if I create a form and tell it the domain and the folder, it will add it to the bottom of the htaccess file?

它工作正常,但我们计划拥有数百个网站,手动将代码片段添加到 htaccess 可能会很烦人。由于我更改的是domain.com/folder,如果我创建一个表单并告诉它域和文件,有没有办法使用 PHP 动态添加到 .htaccess 文件的底部,它会添加它到 htaccess 文件的底部?

That would save so much time.

那会节省很多时间。

Thanks so much.

非常感谢。

回答by genesis

I really do not recommend to allow php to add ANYTHINGinto .htaccess, it's a big security risk.

我真的不建议允许 php 在.htaccess 中添加任何东西,这是一个很大的安全风险。

//but here is your code
$f = fopen(".htaccess", "a+");
fwrite($f, "your content");
fclose($f);

回答by DevelRoot

Here you go:

干得好:

function writeht($domain, $folder)
{
    $fp = fopen('.htaccess','a+');
    if($fp)
    {
        fwrite($fp,'

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(www\.)?'.str_replace('.','\.',$domain).'$ [NC]
RewriteRule ^(.*)$ /'.$folder.'%{REQUEST_URI}?%{QUERY_STRING} [QSA,L]');
        fclose($fp);
    }
}

//usage: writeht("domain.biz","yourfolder");

Works fine for me with 0644permissions on .htaccess(as php runs under the same user as file's owner)

使用0644权限对我来说效果很好.htaccess(因为 php 在与文件所有者相同的用户下运行)

回答by Daniel A. White

Sure. Its just another file as long as the process has permission to write to the file.

当然。只要进程有权写入该文件,它就只是另一个文件。

回答by Timo Haberkern

A pretty comfortable way is using the PEAR class File_HtAccess. But as told before you shouldn't write the file from a PHP-Script that is accessible via web.

一种非常舒适的方法是使用 PEAR 类File_HtAccess。但是如前所述,您不应该从可通过 Web 访问的 PHP 脚本编写文件。