Рабочий пример записи в fstab для unionfs-fuse
unionfs-fuse#/media/disk1=rw:/media/disk2=rw /media/unionfs_disk fuse allow_other,nobootwait 0 0
allow_other необходим, чтобы кто-то кроме root мог пользоваться смонтированной unionfs-fuse директорией.
Рабочий пример записи в fstab для unionfs-fuse
unionfs-fuse#/media/disk1=rw:/media/disk2=rw /media/unionfs_disk fuse allow_other,nobootwait 0 0
allow_other необходим, чтобы кто-то кроме root мог пользоваться смонтированной unionfs-fuse директорией.
Очень понравился сервис генерации картинок из текста, хотя он и без наворотов. Запишу его сюда, чтобы не забыть.
http://www.email2image.com/Convert-Email-to-Image.aspx
Поскольку sed не использует регулярные выражения, а вместо регулярных выражений использует морально устаревшее, труднообъяснимое, мало понятное непойми что, мы его заменим конструкцией
perl -0777pe 's/search/replace/g' -i filename
Где
-0777 - символ, использующийся в качестве построчного разделителя вместо стандартного \n (значения от 0400 и выше заставят perl обработать сразу весь файл целиком в один заход, но 0777 является общепринятым соглашением для этой цели).
-p - встраивает вводимый вами код на perl в "печатающий цикл", который будет обрабатывать stdin построчно.
-e - Позволяет передать исполняемый код в качестве аргумента, а не файла.
-i - Заменяет строки указанного входного файла на результаты вывода perl.
Живой работающий пример:
perl -0777pe 's#(\s+else[\s]+)cnf="\$1/openssl.cnf"(\s+fi)#$1cnf="\$1/openssl-1\.0\.0\.cnf"$2#g' -i /etc/openvpn/easy-rsa/2.0/whichopensslcnf
Пользителка (пользявка) для .bashrc
greplace()
{
perl -0777pe "$1" -i $2
}
Или, что еще удобней и безопасней (-i надо добавлять вручную, чтоб заменило, а без -i в stdout для отладки выводить будет просто):
greplace()
{
perl -0777pe "$1" $2 $3
}
А теперь заменим все "echo" внутри файла filename на адрес нашего айпишника, который выдаст нам curl из своего stdout (при условии, что сервис по адресу http://myip.dnsomatic.com доступен и работает исправно, чего я гарантировать не могу).
greplace 's/echo/'`curl -s http://myip.dnsomatic.com`'/g' -i filename
На случай, если http://myip.dnsomatic.com или какая-либо другая команда, будет возвращать данные с пробелами или символом ", обернём `curl -s http://myip.dnsomatic.com` в "".
greplace 's/echo/'"`curl -s http://myip.dnsomatic.com`"'/g' -i filename
И ещё можно вынести за скобки s
greplace()
{
perl -0777pe s"$1" $2 $3
}
и писать вот так
greplace /search/replace/g filename
Правда без использования кавычек \ придётся экранировать: \\
greplace /\\s+/_/g filename
Спасибо всем этим прекрасным людям, лучшим сынам своего отечества, без которых этот пост был бы невозможен:
http://stackoverflow.com/questions/3365260/match-and-replace-multiple-newlines-with-a-sed-or-perl-one-liner
http://stackoverflow.com/questions/6302025/perl-flags-pe-pi-p-w-d-i-t
http://perldoc.perl.org/perlrun.html#Command-Switches
Чтобы закрыть доступ к внешнему интернету, необходимо зайти на страницу
127.0.0.1:7657/i2ptunnelmgr
И в свойствах I2P HTTP Proxy и I2P HTTPS Proxy убрать значения "outproxy".
В моём случае это были "false.i2p" и "outproxyng.h2ik.i2p" соответственно.
После чего необходимо перезапустить роутер и дождаться инициализации туннелей.
To close external internet access provided through outproxies:
1. go to 127.0.0.1:7657/i2ptunnelmgr
2. delete "outproxy" value from "I2P HTTP Proxy" and "I2P HTTPS Proxy"
3. restart the i2p router and wait for tunnels initialization
Задание выполнил успешно. Рекомендую.
Нашел функциию в интернете и слегка доработал её под свой стиль.
<?php
/**
* Indents a flat JSON string to make it more human-readable.
*
* @param string $json The original JSON string to process.
*
* @return string Indented version of the original JSON string.
*/
function json_indent($json, $indentStr = " ", $newLine = "n")
{
$ind = 0; // Current indention width
$result = ""; // Resulting string
$indention = ""; // Current indention after newline
$escaped = false; // FALSE or escape character
$strLen = strlen($json);
for($i = 0; $i < $strLen; $i++)
{
// Grab the next character in the string
$char = $json[$i];
if($escaped)
{
if($escaped == $char)
{
// End of escaped sequence
$escaped = false;
}
$result .= $char;
if ($char == "\\" && $i + 1 < $strLen)
{
// Next character will NOT end this sequence
$result .= $json[++$i];
}
continue;
}
if ($char == '"' || $char == "'")
{
// Escape this string
$escaped = $char;
$result .= $char;
continue;
}
if(($char == '{' || $char == '[') )
{
$indention = str_repeat($indentStr, $ind++);
if($i > 0 && $json[$i-1] != "," && $json[$i-1] != "[" && $json[$i-1] != "{")
{
$result .= $newLine . $indention;
}
}
// If this character is the end of an element,
// output a new line and indent the next line
if ($char == '}' || $char == ']')
{
$indention = str_repeat($indentStr, --$ind);
$result .= $newLine . $indention;
}
// Add the character to the result string
if($char == ":")
{
$result .= " $char ";
}
else
{
$result .= $char;
}
// If the last character was the beginning of an element,
// output a new line and indent the next line
if ($char == ',' || $char == '{' || $char == '[')
{
if ($char == '{' || $char == '[')
{
$indention = str_repeat($indentStr, $ind);
}
$result .= $newLine . $indention;
}
}
return $result;
}
Печатает примерно такое:
{
"fileCount" : 2,
"data" :
[
{
"id" : "file.1",
"class" : "file",
"file" : "example_file.1.html",
"display" : "example_file.1",
"extension" : "html",
"size" : 12345,
"hasVersions" : true,
"versions" :
{
"fileCount" : 1,
"data" :
[
{
"id" : "file.1.1",
"class" : "file",
"file" : "example_file.1.1.html",
"display" : "example_file.1.1",
"extension" : "html",
"size" : 12345,
"hasVersions" : false,
"versions" : null
}
]
}
},
{
"id" : "file.2",
"class" : "file",
"file" : "example_file.2.html",
"display" : "example_file.2",
"extension" : "html",
"size" : 12345,
"hasVersions" : false,
"versions" : null
}
]
}
Обратить внимание что сначала вевеве, чтобы не было с шиттп-вевеве на шиттпс-вевеве а потом на без-вевеве-шиттпсю.
Универсальный вариант, остальные сука блядь не работают заебёшься редиректы потом глотать по серверам.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{SERVER_PORT} ^.
RewriteCond %{SERVER_PORT} !443 [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} ^.
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Гори в аду, сраная срань:
Скотское блядской гнидоуёбище высосавшее из меня все тризхамудохуеблядские нервы мразь ::::
Starting with Apache 2.4 you can also use the variable %{REQUEST_SCHEME} to preserve the scheme:
RewriteRule "^" "%{REQUEST_SCHEME}://sub.domain.com:2368%{REQUEST_URI}" [P,QSA,L]
No need to meddle with any conditions this way.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* %{REQUEST_SCHEME}://%1%{REQUEST_URI} [R=301,L]
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Но на серверах, что настраивали дебилы, всё может быть гораздо сложнее:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Beb vnojn dndhn,nstkm ktp^
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Как било на сайти с вевеве (site.ru ----> www.site.ru).
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\..* [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Скобочки .(.*) нужны без них не работает ибо %1 берётся из RewriteCond, а $1 из Rule
Безусловный редирект нахуй и в пизду (без слеша после домена ибо слеш уже воткнут в %{REQUEST_URI}
RewriteEngine on
RewriteRule .* https://__EXAMPLE.COM__%{REQUEST_URI} [R=301,L]
Стили: shimmerproject-Albatross-0396113
Значки: elementary Xfce dark
Шрифты: Ubuntu mono 15
DPI: 110
Неожиданно сам для себя, среди кучи неработающих решений (мой мозг так и не смог осилить в короткие сроки тот волшебный механизм, по которому работает mod_rewrite), я, кажется, нашел наконец решение, которое перенаправит ВСЕ запросы на index.php вне зависимости от того, существует файл, или не существует. И, вдобавок, без жесткого прописывания пути к index.php или названия домена. Автор этого решения добавил также возможность исключать некоторые запросы из перенаправления, так что, если это всё действительно правда и впоследствии не найдется никакой ошибки в работе данных директив, то я буду еще долго писать кипятком.
UPD: Изначальный код оказался неидеальным. Приходится добавить директиву DirectorySlash Off, иначе, если вы захотите убрать trailing slash с URL который попадает на реально существующую директорию, apache будет перенаправлять вас на http://site.com/directory/, а вы его обратно на http://site.com/directory и перенаправление попадёт в цикл, который никогда не завершится.
# Turn rewriting on
Options +FollowSymLinks
DirectorySlash Off
RewriteEngine On
# Redirect requests to index.php
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*\.css$ [NC]
RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]
RewriteCond %{REQUEST_URI} !.*\.js$ [NC]
RewriteRule .* /index.php
Ссылка на оригинал: .htaccess redirect all requests to index.php
Оригинал полностью, на случай, если статья с оригинального сайта внезапно проебётся, как это уже не раз бывало со сслыками в сети Интернет.
htaccess Redirect All Requests to Index.php Script
So for one of my website projects I wanted to create a very basic content management system (of sorts). The plan was to have a header and footer template class, and include these from the ‘index.php’. The bit between the header and footer (‘content’) would then be pulled from another file, depending on the URL.
The basic set-up for this kind of CMS is that all requests are sent to one script, which handles working out which files need to be included based on the request URL. If we’re using Apache as our web server, we can do this easily enough using the .htaccess file.
A htaccess file (also known as a distributed configuration file) allows you to configure your web-server on a per-directory basis. One of the handy features of the htaccess file is that we can invoke server-side modules. We can use the mod_rewrite module to redirect or rewrite certain URL requests.
So to set-up our CMS, we need to rewrite all requests to any file on the server to ‘/index.php’. A first attempt at this might be:
# Turn rewriting on Options +FollowSymLinks RewriteEngine On # Redirect requests to index.php RewriteRule .* /index.phpThis looks OK, until you think about what will actually happen. We’re redirecting ALL requests to ‘index.php’ – including requests to ‘index.php’… They call this infinite loopage in the biz’. Our next (and much better attempt) would be:
# Turn rewriting on Options +FollowSymLinks RewriteEngine On # Redirect requests to index.php RewriteCond %{REQUEST_URI} !=/index.php RewriteRule .* /index.phpThis will work well – unless you have things like images, stylesheets, JavaScript or generally any other files we’ve come to expect in a rich internet experience. We can fix this by also excluding requests to these filetypes from the rewrite:
# Turn rewriting on Options +FollowSymLinks RewriteEngine On # Redirect requests to index.php RewriteCond %{REQUEST_URI} !=/index.php RewriteCond %{REQUEST_URI} !.*\.png$ [NC] RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC] RewriteCond %{REQUEST_URI} !.*\.css$ [NC] RewriteCond %{REQUEST_URI} !.*\.gif$ [NC] RewriteCond %{REQUEST_URI} !.*\.js$ [NC] RewriteRule .* /index.phpAnd there you have it! A (useful) .htaccess file used to redirect all requests to the index.php file! Now for that CMS…
This entry was posted on Sunday, March 14th, 2010 at 6:18 pmand is filed under PHP.