Skip to content

Instantly share code, notes, and snippets.

@maximal
Last active March 30, 2016 10:27
Show Gist options
  • Save maximal/27523b038c75b19ae1a6 to your computer and use it in GitHub Desktop.
Save maximal/27523b038c75b19ae1a6 to your computer and use it in GitHub Desktop.
Translate apache2 config files to nginx ones
<?php
if (count($argv) < 2) {
echo 'Usage: ', $argv[0], ' <apache config files>', PHP_EOL;
exit(1);
}
array_shift($argv);
$dir = getcwd() . DIRECTORY_SEPARATOR;
foreach ($argv as $filename) {
echo 'Reading file: ', $filename, PHP_EOL;
if (!file_exists($filename)) {
echo "\t", 'No file!', PHP_EOL;
continue;
}
$contents = file_get_contents($filename);
$root = null;
$serverNames = null;
$match = null;
if (preg_match_all('/(\s*#\s*)?(ServerName|ServerAlias)\s+([^\s]+)/ui', $contents, $match)) {
foreach ($match[3] as $index => $serverName) {
// Если не комментарий, берём имя хоста
if (trim($match[1][$index]) !== '#') {
$serverNames []= $serverName;
}
}
}
if (preg_match_all('/(\s*#\s*)?(DocumentRoot)\s+([^\s]+)/ui', $contents, $match)) {
foreach ($match[3] as $index => $documentRoot) {
// Если не комментарий, берём имя хоста
if (trim($match[1][$index]) !== '#') {
$root = $documentRoot;
}
}
}
if (!$root) {
echo "\t", 'Root path not found!', PHP_EOL;
continue;
}
if (!$serverNames) {
echo "\t", 'Server names not found!', PHP_EOL;
continue;
}
echo "\t", 'Root: ', $root, PHP_EOL;
echo "\t", 'Server names: ', implode(' ', $serverNames), PHP_EOL;
$outFile = preg_replace(['/\.apache\.conf$/ui', '/\.apache$/ui', '/\.conf$/ui'], '', $filename) . '.nginx';
$outFile = $dir . pathinfo($outFile, PATHINFO_BASENAME);
echo "\t", 'Writing file: ', $outFile, PHP_EOL;
file_put_contents($outFile, nginxTemplate($root, $serverNames));
}
/**
* Получает конфигурацию nginx для заданной корневой директории и имён сервера.
* @param string $root
* @param string[] $serverNames
* @return string
*/
function nginxTemplate($root, $serverNames)
{
return sprintf(
<<<'TPL'
server {
# Имя сервера
server_name %s;
# Базовая директория и индексные файлы
index index.html index.htm index.php;
charset utf-8;
# Статика
location ~* \.(htm|html|txt|css|js|svg|jpg|jpeg|gif|png|bmp|ico|swf|pdf|eot|woff|woff2)$ {
root %s;
# Время жизни браузерного кеша
#expires 14d;
}
# Запрещаем доступ к файлам, начинающимся с .ht: .htaccess, .htpass и прочие
# Нужно при одновременном запуске Nginx и Apache2
location ~ /\.ht {
deny all;
}
# Динамику отдаём Апачу
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
#try_files $uri $uri/ /index.html /index.php;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
proxy_pass http://localhost:8080/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 120;
proxy_send_timeout 120;
proxy_read_timeout 180;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#error_page 500 502 503 504 /50x.html;
#location = /50x.html {
# root /usr/share/nginx/www;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php5-fpm:
# fastcgi_pass unix:/var/run/php5-fpm.sock;
# fastcgi_index index.php;
# include fastcgi_params;
#}
# Порты. 80 — по умолчанию
#listen 80; ## listen for ipv4; this line is default and implied
#listen [::]:80 default_server ipv6only=on; ## listen for ipv6
}
TPL
,
implode(' ', $serverNames),
$root
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment