Страници: [1] 2
 1 
 -: January 18, 2010, 09:02:50 pm 
Започната от ron - Последна публикация от ron
Код:
DBCC SHRINKFILE(Pubs_log, 100)
BACKUP log Pubs WITH TRUNCATE_ONLY
DBCC SHRINKFILE(Pubs_log, 100)


 2 
 -: July 21, 2009, 11:27:09 pm 
Започната от ron - Последна публикация от ron
When making multi-boot systems or re-organizing your disks you may be unlucky to find your grub install is either partially or completely removed.

The simplest way to fix this is to boot a livecd but what should you do once the live cd is loaded, especially if you enter grub-install or grub and then find /boot/grub/stage1 and all you get is

Fatal: Error 15

The following are a few quick steps to fix grub using chroot

First make your life easier by getting into a full root session

Код:
ubuntu@ubuntu:~$ sudo su

now mount your ubuntu install

Код:
root@ubuntu:/home/ubuntu# mount /dev/hda5 /mnt

Next bind your real devices so that the grub command can work

Код:
root@ubuntu:/home/ubuntu# mount -o bind /dev /mnt/dev
root@ubuntu:/home/ubuntu# mount -o bind /proc /mnt/proc

Enter the chroot session

Код:
root@ubuntu:/home/ubuntu# chroot /mnt
root@ubuntu:/# grub
grub> find /boot/grub/stage1
find /boot/grub/stage1
 (hd0,1)
 (hd0,4)

My root disk was installed on partition 5 so now set that as root

Код:
grub> root (hd0,4) root (hd0,4)

install grub

Код:
grub> setup (hd0)
setup (hd0)
 Checking if "/boot/grub/stage1" exists... yes
 Checking if "/boot/grub/stage2" exists... yes
 Checking if "/boot/grub/e2fs_stage1_5" exists... yes
 Running "embed /boot/grub/e2fs_stage1_5 (hd0)"...  16 sectors are embedded.
succeeded
 Running "install /boot/grub/stage1 (hd0) (hd0)1+16 p (hd0,4)/boot/grub/stage2 /boot/grub/menu.lst"... succeeded
Done.

Now quit and restart your machine

Код:
grub> quit
exit
reboot

 3 
 -: April 07, 2009, 12:51:28 am 
Започната от ron - Последна публикация от ron
Един трик който може да ви свърши дяволски полезна работа ако е нужно да рестартирате Cold Fusion на сървър и да запазите сесиите на клиентите:

Код:
taskkill /F /IM swsoc.exe /T
net stop "ColdFusion MX 7 ODBC Server"
net start "ColdFusion MX 7 ODBC Server"


може да се направи като batch файл също

 4 
 -: February 26, 2009, 01:36:48 am 
Започната от ron - Последна публикация от ron
   IPCHAINS-HOWTO_BG 1.01
   
   Тук по принцип трябва да има забележки за лиценза и за това, че автора не носи никаква отговорност, но аз ще пропусна това поради ненужност - на който му трябва това, може спокоино да го прочете в оригиналния IPCHAINS-HOWTO. Този документ представлява почити пълен превод на оригиналния.

   Какво е това ipchains.

   Linux ipchains това е замяна на ipfwadm (който беше портнат от BSD). За работа с него на вас ви трябва ядро по-голямо от 2.1.102.

   Защо да се преминава към ipchains?

   В старите версий на Linux fairwall не работеше с фрагменти на пакетите, имаше 32x битови броячи ( на Intel-процесори), не даваше да се указват типовете на протоколите, различни от TCP, UDP и ICMP, не даваше да се правят големи изменения автоматически, нямаше инверсни правила и беше много тежък за управление.

   Малко информация.

   Целия трафик в мрежата се праща във вид на пакети. В началото на всеки пакет има информация за това от къде идва, тип на пакета и други подобни детайли. Началото на пакета се нарича заглавие (header), останалата част на пакета обикновенно се нарича тяло (body).
   Някой протоколи като TCP, които се използват за web, mail и други, използват понятието "съединение" - преди какъвто и да е пакет с данни да бъде пратен на получателя, минават някои настройващи пакети (със специални заглавия) със съобщения от типа на "аз искам да направя съединение", "добре", "благодаря правя го". И само след това ще тръгнат нормалните пакети с информация.
   Филтър на пакети - това е част от програмното осигуряване, която гледа заглавията на пакетите и или го пуска по-нататък или забранява неговото по-нататъшно движение. Има известно различие между понятията "забрана" (deny) и "отказ" (reject). "Забрана" - това е когато пакет от изпращача се отхвърля от системата така, че изпращача мисли, че пакета не е пристигнал до получателя, а "Отказ" - това е когато изпращача се известява за това, че неговия пакет е бил отказан от получателя.

   Защо вообще ни е нужен филтър на пакетите?

   Управление.
   Когато вашия Linux е включен към различни мрежи (и към internet в това число), вие трябва да имате възможност да управлявате, с който и да е поток от данни, минаващи през вашата система. Например, вие трябва да бъдете сигурни, че който и да е пакет от вътрешната мрежа, който може да съдържа важна информация няма да отиде в просторите на internet.

   Безопасност.
   Когато Linux стои един на един с хаоса на internet и в добавка служи за мост към internet за машините от вътрешната мрежа, вие трябва да бъдете сигурни кой и къде ходи през моста. Например вие искате да се разходите в internet, но не искате вашата машина да бъде сървър (а вие сигурни ли сте, че всичките ви потребители имат пароли и излишните сервизи са затворени ?). С наличието на firewall тези проблеми се решават бързо и лесно.

   Хитрост ;-)
   По някога някоя неправилно настроена машина в локалната мрежа или потребител, който поради незнание или поради зъл умисъл започнат да пращат във външната мрежа различни пакети (започвайки от нюкове и завършвайки с пакети от троянци). Та така филтъра на пакетите, ще ви позволи да избегнете такива случаи и ще ви уведоми, какво се е случило автоматически и няма да ви кара да сидите и да контролирате трафика ръчно.

   Как да се инсталира филтър на пакети?
   На вас ви е нужно ядро, което е компилирано заедно с филтър на пакети. Погледнете за файла /proc/net/ip_fwchains - ако го виждате то тогава всичко е наред. Ако не го виждате, то тогава на вас ви е нужно да вземете ядро 2.1.102 или по-голямо. Ако вашето ядро е от серията 2.0, то тогава ви е необходим специален patch. Преконфигурираите си ядрото така, че в него да са включени опциите IP firewalling. В /usr/src/linux/.config за ядрата 2.1 и 2.2 е необходимо да бъдат включени следните опции:
   CONFIG_FIREWALL=y
   CONFIG_IP_FIREWALL=y
Така също трябва да си свалите ipchains, която ще управлява филтъра на пакети в ядрото. Всички последни дистрибутиви на Linux, които са основани на ядрата 2.1 и 2.2 имат ipchains.

   Как пакетите минават през филтрите.
   Ядрото стартира с три списъка на правила, тези правила се наричат правила на fairwall или просто вериги (chains). Тези три вериги се наричат input (входна), output (изходна) и forward (препращане). Когато пакета идва (да кажем от мрежовата карта), ядрото използва входната верига за да определи дали може пакета да се предвижи по-нататък. Ако пакета мине тази проверка то той продължава своето движение (това също така се нарича роутинг). Ако пакета е предназначен за друга машина то ядрото преглежда веригата препращане (forward). И на края преди пакета да излезне, ядрото гледа изходната верига.
   Верига - това е списък от правила. Всяко правило изглежда така "ако заглавието на пакета съдържа това и това, то прави с пакета това". Ако правилото не съответства на заглавието на пакета, ядрото гледа на следващото правило във веригата. И нa карая, ако пакета е минал цялата верига от правила и нито едно правило не е съответствало, ядрото гледа на правилата от веригата. В защитените системи пакета обикновенно се отказва или забранява.

                       ACCEPT/
                      REDIRECT                                        ACCEPT
  --> C --> S --> ______ --> D --> ~~~~~~~~ --> local ------> _______ -->
      h  -> a    |input |    e    {Routing } |  __|____ -->->|output |
      e  |  n    |Chain |    m    {Decision} | |forward|   | |Chain  |
      c  |  i    |______|    a     ~~~~~~~~  | |Chain  |   | |_______|
      k  |  t       |        s        |      | |_______|   |     |
      s  |  y       |        q        |      |     |       |     |
      u  |  |       v        e        v      |     |       |     v
      m  |  |     DENY/      r  Local Process|     v       |   DENY/
      |  |  v    REJECT      a        |-------   DENY/     |  REJECT
      |  |DENY               d        |         REJECT     |
      v  |                   e -------+---------------------
     DENY|                            |
         ------------------------------

   Последователно описание на всеки стадий.

   Проверка на контролната сума (Checksum) - ядрото проверява пакета за цялост и коректност на заглавията. Ако пакета не отговаря на тези условия той се отказва.

   Назначение (Sanity) - ядрото проверява за кого е предназначен пакет, защо и къде. Много от пакетите се отсяват именно на този стадий, но приоритета на "входена" (input) верига е по-горе.

   Входна верига (input) - това е първата верига, с помоща на която филтъра отсеива пакетите. Ако решението на тази верига не е "отказ" (REJECT) или "забрана" (DENY), то тогава пакета продължава своето движение.

   Демаскарад (Demasquaerade) - ако пакета - това е отговор на предишен маскараден пакет, той се демаскирадира и веднага се пуска на входната верига. Ако вие не използвате маскарадинг, вие можете мислено да изтриете това място от рисунката.

   Роутинг (routing) - полето "получател" на пакета се анализира частта на кода, която е ответствена за това къде ще отиде по-нататък - за локална обработка или ще бъде препратен към друга машина (вижте веригата "препращане" (forward)).

   Локална обработка (local) - задача, пусната на локалната машина може да получи пакета само след като той мине роутинга и може да праща пакети в отговор (които, ще минат през изходната верига и след това през входната верига на интерфейса "lo", ако пакета е предназначен за процес на тази машина или ще излезне през изходната верига).

   Ако пакета не е създаден от задача на локалната машина, то се проверява веригата "препращане" (forward), иначе пакета отива направо на "изходната" (output) верига.

   Веригата "препращане" (forward) - тази връзка минават всички пакети, които са предназначени за транзитно преминаване през системата.

   "Изходна" (output) верига - през тази верига минават всички пакети, които се изпращат от тази машина.



   Използване на ipchains.

   Първо проверете каква версия на ipchains имате на машината си.
# ipchains --version
ipchains 1.3.5, 26-June-1998

   Този документ се отнася именно за тази версия на програмата.

   ipchains има man-документация, но ако ви е неохоимо да разберете повече за пътищата на приминаване на пакетите, вие можете да проверите ръководството за програмиране на интерфейси (man 4 ipfw) или файл net/ipv4/ipfw.c в сорсовете на ядрото, те са достатъчно компетентни по този въпрос ;-).

   Има няколко различни неща, които могат да е правят с веригите. Първо - това е опериране с цели вериги. Ядрото стартира с три вградени вериги - "входна", "изходна", препращане" (input, output, forward) - тях вие не можете да махнете. По долу е показано какво може да се прави.

   Създаване на нова верига (-N)
   Махане на празна верига (-X)
   Смяна на правилата за вградени вериги (-P)
   Списък на всички правила на веригата (-L)
   Изчистване на веригата от правила (-F)
   Изтриване на броячите на пакети и байти във всички правила на веригите (-Z)

   Има няколко начина за манипулиране на правилата вътре в веригата.

   Добавяне на ново правило към веригата (-A)
   Да се вмъкне ново правило на указана позиция във веригата (-I)
   Да се замени правило в указана позиция във веригата (-R)
   Да се махне правило от указана позиция (-D)
   Да се махне първото правило, което сработва във веригата (-D)

   Има още няколко операции за маскарадинг.

   Да се покажат текущите съединения чрез маскарадинг (-M -L)
   Да се установят тайм-аути за маскарадинга (-M -S)

   В края има команди, които ви позволяват да проверите, какво се е случило с даден пакет, ако той тръгне през указаната верига.

   Операции с едно правило.

   Това са основни операции в ipchains - манипулация с правилата. Обикновенно, вие можете да изпробвате командите добави (-А) и изтрии (-D) правило. Аналогично и с командите вмъкни (-I) и замени (-R) - синтаксиса им е практически еднакъв.
   Всяко правило установява списък с условия, които пакета трябва да има и какво да се прави с него ако условията съвпадат. За пример даите да забраним всички ICMP пакети, които идват от адреса 127.0.0.1. В нашия случай протокола трябва да бъде ICMP и адрес на източника 127.0.0.1 - за такива условия "забрани".
   Адрес 127.0.0.1 - това е интерфейс-тапа, който го има даже, ако вие нямате реални мережови съединения. Вие можете да използвате програмата ping  за генериране на тези пакети (тя просто праща пакети от типа на ICMP 8 (echo request), на което обикновенно всички добронамерени системи обикновенно отговарят с пакети от типа ICMP 0 (echo reply)). Това ще ни трябва на нас за тестване.

# ping -c 1 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.2 ms

--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.2/0.2/0.2 ms
# ipchains -A input -s 127.0.0.1 -p icmp -j DENY
# ping -c 1 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
#

   Вие виждате, че първия ping мина успешно (опцията "-c 1 казва на ping-а, четрябва да прати само един пакет).

   След това ние добавихме (-A) във "входната" верига правило, което указва на това, че пакетите 127.0.0.1 (-s 127.0.0.1) с протокол ICMP (-p ICMP) трябва да се забраняват (-j DENY).

   След това ние проверихме нашето правило, използвайки втория ping. Той малко почака преди да се предаде, очаквайки пакет с отговор, който никога няма да дойде.

   Не можем да махнем правилото по два начина. Тъй като знаем че имаме само едно правило, ние можем да използваме премахване на правило по номер, ето така:
#ipchains -D input 1
   Това маха правило номер 1 от изходната верига.
   Втория начин - това е огледално изображение на командата "добави", но със замяна на -A с -D. Този начин е полезен когато вие имате пълна с правила верига и не искате да смятате кое по номер е това правило. В този случай можете да направите следното:
#ipchains -D input -s 127.0.0.1 -p icmp -j DENY
   Синтаксиса след командата (-D) трябва да съвпада със синтаксиса на командата -A (или -I и -R), с която и беше зададено това правило. Ако има няколко еднакви правила в различни вериги само първото правило ще бъде махнато.

   Спецификация за филтрите.

   Ние ще използваме -p за посочим на протокола и -s за посочим на адреса на източника, но има и други опции, които сочат други опции на пакетите. Те ще бъдат описани по-долу.

   Посочване на ip-адресите на източниците и получателите.

   ip-адресите на източниците (-s) и на получателите (-d) могат да се посочат по 4-ри начина. Обикновенно тях ги описват с пълните имена, например "localhost" или "linux.org". Втория начин - посочване на пълния ip-адрес, например 127.0.0.1. Третия и четвърти начини дават възможност да се посочват групи от ip адреси, например "62.76.19.0/24" или "62.76.19.0/255.255.255.0". И двата варианта сочат към адрсите от 62.76.19.0 включително до 62.76.19.255. Цифрите след "/" сочат каква част от ip адреса ще бъде значима. По подразбиране се приема "/32" или "/255.255.255.255" (влизат всички ip адреси).
За посочване, на които и да е ip адрес е възможно изолзването на "/0", например
#ipchains -A input -s 0/0 -j DENY
Това ще предизвика същия ефект, както и без използването на -s вообще.

   Посочване на инверсия.

   Много флагове, включвайки -s и -d могат да имат трети аргумент във
вида на "!", за изчисление на адресите, които НЕ попадат в посочването.
Например под "-s ! localhost" попадат всички пакети, които не идват от
localhost.

   Посочване на протокола.

   Протокола може да бъде посочен с помощана фалага -p. Протокола може да бъде номер (ако вие не знаете значенията на номерата за протокола ip) или едно от следните значения: TCP, UDP или ICMP. Регистъра няма значения, tcp е същото като TCP. Протоколите също така могат да бъдат инвертирани с помоща на "!", например "-s ! TCP" указва на тези протоколи, които не са TCP.

   Посочване на TCP и UDP портове.

   Когато са посочени протоколите TCP или UDP е възможен и трети аргумент, който сочи към TCP&UDP портове или тяхен диапазон (включвайки крайните портове). Диапазона се посочва с помоща на символа ":", например "6000:6010" сочи към 11 порта, от 6000 до 6010 включително. Ако долната граница не е посочена то тя се приема за 0. Ако горната граница не е посочена, тя се приема равна на 65535. Например за посочване на TCP съединения идващи от портове по-ниски от 1024, синтаксиса ще бъде следния "-p TCP -s 0.0.0.0/0 :1024". Така също портовете могат да бъдат посочени по име, например www (за превод на численото значение погледнете файла /etc/services).

   Номерата на портовете също така могат да бъдат инвертирани с помоща на "!". Например, за посочването, на които и да е TCP пакет освен WWW пакетите е нужно да се посочи
"p TCP -d 0.0.0.0/0 ! www"
Важно е да се разбере, че
"p TCP -d ! 192.168.1.1 www"
МНОГО СИЛНО СЕ РАЗЛИЧАВА от
"-p TCP -d 192.168.1.1 ! www"
   Първото правило посочва към, които и да е TCP пакети на WWW порт, ня която и да е машина, но не и на 192.168.1.1. Второто правило посочва към, което и да е TCP съединение на 192.168.1.1, на който и да е порт с изключение на WWW.
Обединявайки тези правила, ще получим
-p TCP -d ! 192.168.1.1 ! www
то ест, на която и да е машина освен 192.168.1.1, на който и да е порт освен WWW.

   Посочване на типовете и кодовете на ICMP.

   ICPM също така допуска и използването на допълнителни аргументи, но ICMP няма портове (ICMP използва тип и код за предаване на данни).
   Вие можете да посочите имената на ICMP пакетите (ipchains -h ICMP за списък на имената) след ключа -s или численото значение на типа и кода на ICMP, където типа следва след ключа -s, а кода след ключа -d.
   ICMP имената не са толкова дълги, достатъчно е да се укажат няколко символа, по които могат еднозначно да се различат от други.
   По-долу е показана малка таблица на ICMP типовете.

   Номер    Име                      Нужен е за
       
        0       echo-reply               ping
   3       destination-unreachable   за който и да е TCP/UDP трафик.
   5       redirect                 за роутинг, ако не е пуснат демон на роутинга
   8       echo-request             ping
   11      time-exceeded            traceroute

Запомнете, че ICMP типовете не могат да бъдат използвани заедно с "!"
НЕ БЛОКИРАЙТЕ 3 тип на ICMP пакетите !!!!!!!

   Посочване на интерфейса.

   Ключа -i сочи към имета на интерфейса за обработка. Интерфейс това е физическо устройство, през което "ходят" пакетите. За издаване на списък на работищите интерфейси има команда ifconfig, която ще ви покаже списък на "вдигнатите" интерфейси.
   Интерфейс за входните пакети (т.е. за тези, които минават "входната" верига) - това е едно и също като изходния интерфейс.
   Разрешава се да се посочват имената на тези интерфейси, които в дадения момент не съществуват. Правилата няма да се изпълняват до тогава докато тези интерфейси не се появят. Това може да бъде полезно за временни съединения с модем (ppp0) и за други подобни случаи.
   Също така се разрешава да се посочва след името на интерфейса знак "+". Това посочва към обработка на всичките интерфейиси започващи с тези букви. Например за обработка на всички PPP съединения, може да се посочи -i ppp+.
   Разрешава се заедно с името на интерфейса да се посочва знак "!" за отрицание (т.е. да се обработват всички интерфейси освен посочения).

   Посочване само на TCP SYN пакети.

   Тази опция е полезна за разрешаване на TCP съединения само в една посока. За пример, вие искате да се разхождате по чужд сървър, но да забраните на чуждия сървър да установява съединение с вас. Обикновенното решение е да се забрани приемането на TCP пакети, идващи от сървъра не върви, тъи като на сървъра му е нужно по някакъв начин да ви предава инфрмация.

   Решението се състой в това, че да се забраняват само тези пакети, които искат да направят съединение. Тези пакети се наричат SYN-пакети (честно казано това са обикновенни пакети само, че с вдигнат SYN флаг).
   Ключа -y се използва точно за това. За пример, ако е необходимо да се разрешат съединения с 192.169.1.1 е необходимо да се напише следното:
-p TCP -s 192.168.1.1 -y
   Както обикновенно този ключ може да се използва заедно с флага "!", разрешавайки които и да е съединения освен пакетите за инициализация на съединение.

   Обработка на фрагменти.

   Понякога пакета е много голям за да се предаде целия. Когато това се случи пакета се разбва на няколко фрагмента и се праща във вид на няколко пакета. Другата страна приема всичките пакети от фрагментите и сабира от тях един голям.
   Проблема се състои в това, че служебната информация (адресите на изпращача и получателя, порт, ICMP тип и код и други) нужна на ядрото се съдържа само в първия фрагмент.
   Ако вашата машина е включена само във външна мрежа този проблем може да се реши лесно. При компилация на ядрото поставете always defragmet в "Y". Тази опция посочва на ядрото винаги да сабира всички фрагменти преди по-нататъшна работа.
   В друг случай важно е да се разбере как фарагментите минават списъка с правила. Което и да е правило, което се опитва да разбере информация за фрагмента не я получава, освен в случая с първия фрагмент. За осигуряване на тази възможност в описанието на правилата е необходимо да се добави ключа -f.
   За осигуряване сработването на правилото само на првия фаргмент, ключа -f може да се използва със знака "!".
   Обикновенно това се използва за защита на преминаване на втори и следващи пакети от тогава, както първия фрагмент е минал филтрация и за защита от събиране на фрагментите на хоста-приемник. Това може да бъде опасно тъй като някои машини падат от просто пращане на фрагменти. Аз предупредих ;-).

   За машините, които служат за главни в мрежата - много от пакетите (TCP, UDP и ICMP) идват вече фрагментирани - бъдете внимателни.
   За пример, следното правило ще отхвърля всички фрагменти идваши към 192.168.1.1
ipchains -A output -f -D 192.168.1.1 -j DENY

   Какво става във филтъра на пакети?
   Добре, сега ние знаем всички пътища, по които ние можем да отправяме пакетите. Ако пакета минава правилото, става следното:

1 - Брояча на байтове за това правило се увеличава с размера на пакета (заедно със заглавието)
2 - Брояча на пакети за това правило се увеличава
3 - Ако правилото изисква, информацията за пакета се записва в лог
4 - Ако правилото изисква, полето TypeOfService на пакета се променя
5 - Ако правилото изисква, пакета се маркира (не и за ядрата 2.0)
6 - Проверява се следващото правило по пътя, които следва пакета

   Установяване на указания.

   Дадените ключове позволяват да се укаже на ядрото къде да препраща пакета, който е попаднал под деиствие на правилата. ipchains използва ключа "-j" (от jump-to - прескочи-към) за указване на адресата на пакета.
   Най-простия случай - това е да не се посочва адресата вообще. Този тип на правила се нарича accounting, те обикновенно се използват преброяването на числото на определен тип пакети. Без значение дали този пакет попада под действие на това правило или не, ядрото все едно ще провери следващите правила във веригата. За пример, за преброяването на числото на пакетите идващи от 192.168.1.1, ние можем да посочим следното:
ipchains -A input -s 192.168.1.1
   Използвайки командата ipchains -L -v вие ще можете да прегледате броячите на пакетите и байтовете за всяко правило.
   Има 6 специални указания, първите три ACCEPT, REJECT и DENY са разбираеми. ACCEPT пропуска пакетите, REJECT отхвърля пакетите с оповестяване на източника, DENY отхвърля пакета така, като че ли той никога не е идвал.

   Следващото указание, MASQ казва на ядрото да направи маскарадинг на пакета. За да работи това правило ядрото трябва да бъде компилирано с поддръжка на IP Masquerading. За уточняване да детаилите четете Masquerading-HOWTO. Това правило ще работи само за веригата "препращане".
   
   Указанието REDIRECT посочва на ядрото да препраща пакета на посочения адрес бе да взима предвид реалния адрес, посочен в заглавието на пакета. Това правило работи само за TCP и UDP протоколите. Допълнително вие можете да укажите порт (номер или име) след "-j REDIRECT". В този случай пакета ще бъде препратен на указания порт, даже ако той е пратен на друг порт. Това правило работи само за входната верига.

   Указание REUTRN посочва на ядрото веднага да пропусне пакета до края на веригата.
   Което и да друго правило сочи към вериги определяеми от потребителя. Пакета преминава правилата на тази верига както обикновенно.

           `input'                         `Test'
 ----------------------------    ----------------------------
 | Rule1: -p ICMP -j REJECT |    | Rule1: -s 192.168.1.1    |
 |--------------------------|    |--------------------------|
 | Rule2: -p TCP -j Test    |    | Rule2: -d 192.168.1.1    |
 |--------------------------|    ----------------------------
 | Rule3: -p UDP -j DENY    |
 ----------------------------

Да вземем TCP пакет, който идва от 192.168.1.1 към 1.2.3.4. Той влиза във входната верига и се проверява правило 1 - не сработва. Правило 2 сработва, но неговото указание е Test и за това следващото правило, което се проверява това е първото правило във веригата Test. 1-то правило не сработва и се проверява 2-то. То съшо не сработва и ние достигнахме края на веригата и се връщаме назад, проверява се правило 3, което също не сработва.

Да опишем пътя на пакета.


                            v    __________________________
     `input'                |   /    `Test'                v
    ------------------------|--/    -----------------------|----
    | Rule1                 | /|    | Rule1                |   |
    |-----------------------|/-|    |----------------------|---|
    | Rule2                 /  |    | Rule2                |   |
    |--------------------------|    -----------------------v----
    | Rule3                 /--+___________________________/
    ------------------------|---
                            v

   Записване на пакетите в лог.

   Ако в правилото е посочен флаг -l, ядрото при сработване на првилото, ще ви даде предупреждение. Този флаг е полезен за експерименти и за известяването ви за идването на някакъв пакет.

   Управление на TypeOfService.

   Има 4 бита в заглавието на пакета, наричани битове TypeOfService (тип на сервиза) - "Minimum Delay" (минимално задържане), "Maximum Throughput" (максимална пропускателна способност), "Maximum Reliability" (максимална достъпност) и "Minimum Cost" (минимална цена). Само един от тези битове може да бъде използван.
   Обикновенно установяват за съединения, отнасящи се към telnet&ftp control минимална задръжка, а за FTP data максимална пропускателна способност. Това се прави по следния начин:
ipchains -A output -p tcp -d 0.0.0.0/0 telnet -t 0x01 0x10
ipchains -A output -p tcp -d 0.0.0.0/0 ftp -t 0x01 0x10
ipchains -A output -p tcp -s 0.0.0.0/0 ftp-data -t 0x01 0x08

Ключа -t има 2 параметъра и двата в шестнадесетичен вид. С първото число и битовете TOS на пакета се изпълнява AND (логическо-и), а с втория XOR (изключващо-или). Това е достатъчно трудно за разбиране, за това ето една таблица


       TOS Име                Значение        Използва се от
       
      Minimum Delay           0x01 0x10       ftp, telnet
      Maximum Throughput      0x01 0x08       ftp-data
      Maximum Reliability     0x01 0x04       snmp
      Minimum Cost            0x01 0x02       nntp

   Маркиране на пакети.

   За съжаление, това все още не е направено, но във всеки случай това няма да го бъде за ядрата 2.0.

   Операций върху цяла верига.

   Много полезно своиство на ipchains е да прави операций над цяла верига. Вие можете да наречете своята верига от правила както искате, с изключение на имената използвани от вградените вериги (input, output, forward) или указанията (MASQ, REDIRECT, DENY, REJECT или RETURN). Името на веригата може да бъде дълго до 8 символа.

   Създаване на нова верига.
   Нека да създадем нова верига. Нека да я наречем test.

   ipchains -N test

   Това е просто, сега можете да слагате правила във веригата.

   Махане на верига.
   Махането на верига е също толкова просто, както и създаването.

   ipchains -X test

   Защо -X ? Чисто и просто нямаше повече подходящи букви ;-).

   Запомнете вие не можете да махнете верига докато тя не е празна!

   Изчистване на верига.
   Най-простия начин да се изчисти верига, това е използването на ключа -F.

   ipchains -F forward

   Ако името на веригата не е посочено всички вериги ще бъдат изчистени.


   Разглеждане на веригите.

   Вое можете да разгледате всики правила във веригата използвайки ключа -L

# ipchains -L input
Chain input (refcnt = 1): (policy ACCEPT)
target     prot opt    source                destination           ports
ACCEPT     icmp -----  anywhere              anywhere              any
# ipchains -L test
Chain test (refcnt = 0):
target     prot opt    source                destination           ports
DENY       icmp -----  localnet/24           anywhere              any
#

refcnt показва колко правила има във веригата. Това число трябва да бъде 0, за да може веригата да се изтрие.

За ключа -L има 3 опций. -n забранява опитите на ipchains да преобразува ip адресите в символически. -v ви показва детайлен списък на правилата. Например

# ipchains -v -L input
Chain input (refcnt = 1): (policy ACCEPT)
 pkts bytes target     prot opt   tosa tosx  ifname    mark        source                destination           ports
   10   840 ACCEPT     icmp ----- 0xFF 0x00  lo                    anywhe                 anywhere              any

Запомнете, че числото на пакетите може да се извежда със съответните суфикси (K, M, G съответно за килобайт, мегабайт и гигабайт). Използвайки -x вие ще можете да извеждате числата в пълен формат.

   Нулиране на броячите.

   Това действие може да бъде направено с помоща на ключа -Z.

   Единствения проблем, който може да възникне в този случай се състой в това, че след командата -L и до командата -Z могат да дойдат няколко пакета, които няма да бъдат отчетени. Изхода от това положение се състой в едновременното използване на ключовете -L и -Z. Но в този случай вие няма да можете да оперирате с една верига - действията ще се осъществяват за всички вериги като за една.

   Установяване на указания за веригата.

   Тази опция е напълно анологична на установяването на указания за правилата с изключение на някои моменти.
   1 - възможни са само указания ACCEPT, DENY, REJECT или MASQ.
   2 - указанието MASQ е възможно само във веригата препращане (forward).
   3 - указанието RETURN трябва да се използва с голямо внимание.

   Операций с маскарадинга.

   Командата за IP маскарадинг -M може да бъде обединена с -L за разглеждане на текущите съединения или със -S за установяването на параметри.
   Командата -L може да бъде използвана с ключовете -n за разглеждането на адресите и портовете на текущите съединения или с -v за по-детайлно разглеждане на съшата информация.
   Командата -S трябва да върви с 3-те параметъра на таймаута всеки в секунди: първия за TCP сесийте, втория за TCP сесийте след пакета FIN и за UDP пакетите. Ако вие не искате да променяте, който и да е от параметрите просто оставете неговото значение на "0".
   Значенията по подразбиране се съдържат във файла '/usr/include/net/ip_masq.h', обикновенно 15 минути, 2 минути и 5 минути съответно.

   Проверка на пакетите.

   Понякога на вас ви трябва да видите, какво се случва с пакета, който влиза по някакъв начин в машината, например, тестиране на веригата за грешки. ipchains има за този случай командата -C.
   За указването на коя точно верига трябва да се тестира, нейното име може да се укаже след командата -C, иначе ядрото започва да минава през веригите започвайки от input.
   За указването на типа на пакетите се прилагат същите ключове, които се използват и при указването на правила за филтрите.
   Например, тестваме TCP SYN пакет от 192.168.1.1 на порт 6000 към 192.168.1.1 порт www, започвайки от входната верига. Това е класическо www съединение.

# ipchains -C input -p tcp -y -s 192.168.1.1 60000 -d 192.168.1.2 www
packet accepted

   Полезни примери.

   За пример ще разгледаме някоя машина.
   Използва се dial-up (-i ppp0), взимат се новини (-p TCP -s news nntp) и поща (-p TCP -s mail pop-3), от време на време има достъп до ftp за обновяване на системата (-p TCP -y -s ftp.cdrom.com ftp-data). Достъп до web през прокси-сървър (-p TCP -d proxy 3128), но на нас не ни трябва реклама от doubleclick.net или от Dilbert Archive (-p TCP -y -d 199.95.207.0/24 & -p TCP -y -d 199.95.208.0/24). Ние не искаме да пукаме потребители до нас по ftp (-p TCP -d $LOCALIP ftp) и вообще в локалната мрежа (-s 192.168.1.0/24).

   1 - ние не искаме нещо или някой да праща пакети към doubleclick.net

# ipchains -A output -d 199.95.207.0/24 -j REJECT
# ipchains -A output -d 199.95.208.0/24 -j REJECT

    2 - ще направим верига ppp-out за правила, които ще дистват по време на връзката ни с интернет

# ipchains -N ppp-out
# ipchains -A output -i ppp0 -j ppp-out

    3 - минимална задръжка за telnet&web

# ipchains -A ppp-out -p TCP -d proxy.virtual.net.au 8080 -t 0x01 0x10
# ipchains -A ppp-out -p TCP -d 0.0.0.0 telnet -t 0x01 0x10

    4 - минимален приоритет за ftp данните, nntp, pop-3

# ipchains -A ppp-out -p TCP -d 0.0.0.0/0 ftp-data -t 0x01 0x02
# ipchains -A ppp-out -p TCP -d 0.0.0.0/0 nntp -t 0x01 0x02
# ipchains -A ppp-out -p TCP -d 0.0.0.0/0 pop-3 -t 0x01 0x02

    5 - ще направим верига за входящи по dial-up пакети

# ipchains -N ppp-in
# ipchains -A input -i ppp0 -j ppp-in

    6 - ще забраним достъпа да вътрешната мрежа

# ipchains -A ppp-in -s 192.168.1.0/24 -l -j DENY

    7 - ще разрешим съединения към DNS, ftp, и данни от ftp само към нас

# ipchains -A ppp-in -p TCP -s 203.29.16.1 -d $LOCALIP dns -j ACCEPT
# ipchains -A ppp-in -p TCP -s 0.0.0.0/0 ftp-data -d $LOCALIP 1024:5999 -j ACCEPT
# ipchains -A ppp-in -p TCP -s 0.0.0.0/0 ftp-data -d $LOCALIP 6010: -j ACCEPT
# ipchains -A ppp-in -p TCP -d $LOCALIP ftp -j ACCEPT

    8 - локалните пакети трябва свободно да си ходят

# ipchains -A input -i lo -j ACCEPT

    9 - ако нито едно от правилата не е сработило, забраняваме пакета

# ipchains -P input DENY

   Съхранение и възтановяване на настройките на fairwall-а.

   Уморително е всеки път да се въвеждат изредените по-горе команди. Има 2 изхода, да се запишат всички команди в шел-скрипт или да се възползваме от ютилитите ipchains-save и ipchains-restore.
# ipchains-save > my_firewall
# ipchains-restore < my_firewall
Как да ги използваме, от примера се вижда. ipchains-save може да има само един параметър - името на запазваната верига, ако то не е посочено то се запазват всички вериги. ipchains-restore има 2 ключа: -v, който описва, какво прави скрипта и -f, който автоматически изчиства съществуващата верига преди възтановяването на правилата в нея.

   По-подробно за това, какво не трябва да се забранява и за различията между ipfwadm и ipchians вие можете да прочетете в оригиналния IPCHAINS-HOWTO. За пускането на нормално работещ firewall е достатъчно и горе посоченото. Не възразявам, ако някой събере сили и преведе останалото и допълни този документ от оригинала ;-).

 5 
 -: January 21, 2009, 10:17:44 pm 
Започната от ron - Последна публикация от ron
Ето как можете лесно да енкоднете MOV или MPG файл в FLV файл.


Код:
ffmpeg -i <името.mpg> -deinterlace -ar 44100 -r 25 -qmin 3 -qmax 6 <името.flv>


 6 
 -: December 23, 2008, 03:34:47 am 
Започната от ron - Последна публикация от ron
# Stop the MySQL Server.

Код:
sudo /etc/init.d/mysql stop


# Start the mysqld configuration.

Код:
sudo mysqld --skip-grant-tables &


# Login to MySQL as root.

Код:
mysql -u root mysql

# Add user
Код:
CREATE USER 'bob'@'localhost' IDENTIFIED BY '654321';

# Replace YOURNEWPASSWORD with your new password!

Код:
UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root'; FLUSH PRIVILEGES; exit;


 7 
 -: December 23, 2008, 01:28:20 am 
Започната от ron - Последна публикация от ron
General Information

.htaccess Definition1

Apache server software provides distributed (i.e., directory-level) configuration via Hypertext Access files. These .htaccess files enable the localized fine-tuning of Apache’s universal system-configuration directives, which are defined in Apache’s main configuration file. The localized .htaccess directives must operate from within a file named .htaccess. The user must have appropriate file permissions to access and/or edit the .htaccess file. Further, .htaccess file permissions should never allow world write access — a secure permissions setting is “644”, which allows universal read access and user-only write access. Finally, .htaccess rules apply to the parent directory and all subdirectories. Thus to apply configuration rules to an entire website, place the .htaccess file in the root directory of the site.

Commenting .htaccess Code

Comments are essential to maintaining control over any involved portion of code. Comments in .htaccess code are fashioned on a per-line basis, with each line of comments beginning with a pound sign #. Thus, comments spanning multiple lines in the .htaccess file require multiple pound signs. Further, due to the extremely volatile nature of htaccess voodoo, it is wise to include only alphanumeric characters (and perhaps a few dashes and underscores) in any .htaccess comments.

Important Notes for .htaccess Noobs

As a configuration file, .htaccess is very powerful. Even the slightest syntax error (like a missing space) can result in severe server malfunction. Thus it is crucial to make backup copies of everything related to your site (including any original .htaccess files) before working with your Hypertext Access file(s). It is also important to check your entire website thoroughly after making any changes to your .htaccess file. If any errors or other problems are encountered, employ your backups immediately to restore original functionality.

Performance Issues

.htaccess directives provide directory-level configuration without requiring access to Apache’s main server cofiguration file (httpd.conf). However, due to performance and security concerns, the main configuration file should always be used for server directives whenever possible. For example, when a server is configured to process .htaccess directives, Apache must search every directory within the domain and load any and all .htaccess files upon every document request. This results in increased page processing time and thus decreases performance. Such a performance hit may be unnoticeable for sites with light traffic, but becomes a more serious issue for more popular websites. Therefore, .htaccess files should only be used when the main server configuration file is inaccessible. See the “Performance Tricks” section of this article for more information.

Regex Character Definitions for htaccess2

#
    the # instructs the server to ignore the line. used for including comments. each line of comments requires it’s own #. when including comments, it is good practice to use only letters, numbers, dashes, and underscores. this practice will help eliminate/avoid potential server parsing errors.
[F]
    Forbidden: instructs the server to return a 403 Forbidden to the client.
[L]
    Last rule: instructs the server to stop rewriting after the preceding directive is processed.
[N]
    Next: instructs Apache to rerun the rewrite rule until all rewriting directives have been achieved.
[G]
    Gone: instructs the server to deliver Gone (no longer exists) status message.
[P]
    Proxy: instructs server to handle requests by mod_proxy
[C]
    Chain: instructs server to chain the current rule with the previous rule.
[R]
    Redirect: instructs Apache to issue a redirect, causing the browser to request the rewritten/modified URL.
[NC]
    No Case: defines any associated argument as case-insensitive. i.e., "NC" = "No Case".
[PT]
    Pass Through: instructs mod_rewrite to pass the rewritten URL back to Apache for further processing.
[OR]
    Or: specifies a logical "or" that ties two expressions together such that either one proving true will cause the associated rule to be applied.
[NE]
    No Escape: instructs the server to parse output without escaping characters.
[NS]
    No Subrequest: instructs the server to skip the directive if internal sub-request.
[QSA]
    Append Query String: directs server to add the query string to the end of the expression (URL).
[S=x]
    Skip: instructs the server to skip the next "x" number of rules if a match is detected.
[E=variable:value]
    Environmental Variable: instructs the server to set the environmental variable "variable" to "value".
[T=MIME-type]
    Mime Type: declares the mime type of the target resource.
[]
    specifies a character class, in which any character within the brackets will be a match. e.g., [xyz] will match either an x, y, or z.
[]+
    character class in which any combination of items within the brackets will be a match. e.g., [xyz]+ will match any number of x’s, y’s, z’s, or any combination of these characters.
[^]
    specifies not within a character class. e.g., [^xyz] will match any character that is neither x, y, nor z.
[a-z]
    a dash (-) between two characters within a character class ([]) denotes the range of characters between them. e.g., [a-zA-Z] matches all lowercase and uppercase letters from a to z.
a{n}
    specifies an exact number, n, of the preceding character. e.g., x{3} matches exactly three x’s.
a{n,}
    specifies n or more of the preceding character. e.g., x{3,} matches three or more x’s.
a{n,m}
    specifies a range of numbers, between n and m, of the preceding character. e.g., x{3,7} matches three, four, five, six, or seven x’s.
()
    used to group characters together, thereby considering them as a single unit. e.g., (perishable)?press will match press, with or without the perishable prefix.
^
    denotes the beginning of a regex (regex = regular expression) test string. i.e., begin argument with the proceeding character.
$
    denotes the end of a regex (regex = regular expression) test string. i.e., end argument with the previous character.
?
    declares as optional the preceding character. e.g., monzas? will match monza or monzas, while mon(za)? will match either mon or monza. i.e., x? matches zero or one of x.
!
    declares negation. e.g., “!string” matches everything except “string”.
.
    a dot (or period) indicates any single arbitrary character.
-
    instructs “not to” rewrite the URL, as in “...domain.com.* - [F]”.
+
    matches one or more of the preceding character. e.g., G+ matches one or more G’s, while "+" will match one or more characters of any kind.
*
    matches zero or more of the preceding character. e.g., use “.*” as a wildcard.
|
    declares a logical “or” operator. for example, (x|y) matches x or y.
\
    escapes special characters ( ^ $ ! . * | ). e.g., use “\.” to indicate/escape a literal dot.
\.
    indicates a literal dot (escaped).
/*
    zero or more slashes.
.*
    zero or more arbitrary characters.
^$
    defines an empty string.
^.*$
    the standard pattern for matching everything.
[^/.]
    defines one character that is neither a slash nor a dot.
[^/.]+
    defines any number of characters which contains neither slash nor dot.
http://
    this is a literal statement — in this case, the literal character string, “http://”.
^domain.*
    defines a string that begins with the term “domain”, which then may be proceeded by any number of any characters.
^domain\.com$
    defines the exact string “domain.com”.
-d
    tests if string is an existing directory
-f
    tests if string is an existing file
-s
    tests if file in test string has a non-zero value

Redirection Header Codes

    * 301 - Moved Permanently
    * 302 - Moved Temporarily
    * 403 - Forbidden
    * 404 - Not Found
    * 410 - Gone

Essentials

Commenting your htaccess Files

It is an excellent idea to consistenly and logically comment your htaccess files. Any line in an htaccess file that begins with the pound sign ( # ) tells the server to ignore it. Multiple lines require multiple pounds and use letters/numbers/dash/underscore only:

# this is a comment
# each line must have its own pound sign
# use only alphanumeric characters along with dashes - and underscores _

Enable Basic Rewriting

Certain servers may not have “mod_rewrite” enabled by default. To ensure mod_rewrite (basic rewriting) is enabled throughout your site, add the following line once to your site’s root htaccess file:

# enable basic rewriting
RewriteEngine on

Enable Symbolic Links

Enable symbolic links (symlinks) by adding the following directive to the target directory’s htaccess file. Note: for the FollowSymLinks directive to function, AllowOverride Options privileges must be enabled from within the server configuration file (see proceeding paragraph for more information):

# enable symbolic links
Options +FollowSymLinks

Enable AllowOverride

For directives that require AllowOverride in order to function, such as FollowSymLinks (see above paragraph), the following directive must be added to the server configuration file. For performance considerations, it is important to only enable AllowOverride in the specific directory or directories in which it is required. In the following code chunk, we are enabling the AllowOverride privs only in the specified directory (/www/replace/this/with/actual/directory). Refer to this section for more information about AllowOverride and performance enhancement:

# enable allowoverride privileges
<Directory /www/replace/this/with/actual/directory>
 AllowOverride Options
</Directory>

Rename the htaccess File

Not every system enjoys the extension-only format of htaccess files. Fortunately, you can rename them to whatever you wish, granted the name is valid on your system. Note: This directive must be placed in the server-wide configuration file or it will not work:

# rename htaccess files
AccessFileName ht.access

Note: If you rename your htaccess files, remember to update any associated configuration settings. For example, if you are protecting your htaccess file via FilesMatch, remember to inform it of the renamed files:

# protect renamed htaccess files
<FilesMatch "^ht\.">
 Order deny,allow
 Deny from all
</FilesMatch>

Retain Rules Defined in httpd.conf

Save yourself time and effort by defining replicate rules for multiple virtual hosts once and only once via your httpd.conf file. Then, simply instruct your target htaccess file(s) to inheret the httpd.conf rules by including this directive:

RewriteOptions Inherit
Performance

Improving Performance via AllowOverride

Limit the extent to which htaccess files decrease performance by enabling AllowOverride only in required directories. For example, if AllowOverride is enabled throughout the entire site, the server must dig through every directory, searching for htaccess files that may not even exist. To prevent this, we disable the AllowOverride in the site’s root htaccess file and then enable AllowOverride only in required directories via the server config file (refer to this section for more information). Note: if you do not have access to your site’s server config file and also need AllowOverride privileges, do not use this directive:

# increase performance by disabling allowoverride
AllowOverride None

Improving Performance by Passing the Character Set

Prevent certain 500 error displays by passing the default character set parameter before you get there. Note: replace the “utf-8” below with the charset that your site is using:

# pass the default character set
AddDefaultCharset utf-8

Improving Performance by Preserving Bandwidth

To increase performance on PHP enabled servers, add the following directive:

# preserve bandwidth for PHP enabled servers
<ifmodule mod_php4.c>
 php_value zlib.output_compression 16386
</ifmodule>

Disable the Server Signature

Here we are disabling the digital signature that would otherwise identify the server:

# disable the server signature
ServerSignature Off

Set the Server Timezone

Here we are instructing the server to synchronize chronologically according to the time zone of some specified state:

# set the server timezone
SetEnv TZ America/Washington

Set the Email Address for the Server Administrator

Here we are specifying the default email address for the server administrator:

# set the server administrator email
SetEnv SERVER_ADMIN default@domain.com

Improve Site Transfer Speed by Enabling File Caching

The htaccess genius over at askapache.com explains how to dramatically improve your site’s transfer speed by enabling file caching 3. Using time in seconds* to indicate the duration for which cached content should endure, we may generalize the htaccess rules as such (edit file types and time value to suit your needs):

# cache images and flash content for one month
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>

# cache text, css, and javascript files for one week
<FilesMatch ".(js|css|pdf|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>

# cache html and htm files for one day
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>

# implement minimal caching during site development
<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|htm|txt)$">
Header set Cache-Control "max-age=5"
</FilesMatch>

# explicitly disable caching for scripts and other dynamic files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

# alternate method for file caching
ExpiresActive On
ExpiresDefault A604800 # 1 week
ExpiresByType image/x-icon A2419200 # 1 month
ExpiresByType application/x-javascript A2419200 # 1 month
ExpiresByType text/css A2419200 # 1 month
ExpiresByType text/html A300 # 5 minutes
# disable caching for scripts and other dynamic files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
ExpiresActive Off
</FilesMatch>

    * * Convert common time intervals into seconds:
    * 300 = 5 minutes
    * 2700 = 45 minutes
    * 3600 = 1 hour
    * 54000 = 15 hours
    * 86400 = 1 day
    * 518400 = 6 days
    * 604800 = 1 week
    * 1814400 = 3 weeks
    * 2419200 = 1 month
    * 26611200 = 11 months
    * 29030400 = 1 year = never expires

Set the default language and character set

Here is an easy way to set the default language for pages served by your server (edit the language to suit your needs):

# set the default language
DefaultLanguage en-US

Likewise, here we are setting the default character set (edit to taste):

# set the default character set
AddDefaultCharset UTF-8

Declare specific/additional MIME types

# add various mime types
AddType application/x-shockwave-flash .swf
AddType video/x-flv .flv
AddType image/x-icon .ico

Send character set and other headers without meta tags

# send the language tag and default character set
# AddType 'text/html; charset=UTF-8' html
AddDefaultCharset UTF-8
DefaultLanguage en-US

Limit server request methods to GET and PUT

# limit server request methods to GET and PUT
Options -ExecCGI -Indexes -All
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD) RewriteRule .* - [F]

Selectively process files according to server request method

# process files according to server request method
Script PUT /cgi-bin/upload.cgi
Script GET /cgi-bin/download.cgi

Execute various file types through a cgi script

For those special occasions where certain file types need to be processed with some specific cgi script, let em know who sent ya:

# execute all png files via png-script.cgi
Action image/png /cgi-bin/png-script.cgi
Security

Prevent Acess to .htaccess

Add the following code block to your htaccess file to add an extra layer of security. Any attempts to access the htaccess file will result in a 403 error message. Of course, your first layer of defense to protect htaccess files involves setting htaccess file permissions via CHMOD to 644:

# secure htaccess file
<Files .htaccess>
 order allow,deny
 deny from all
</Files>

Prevent Acess to a Specific File

To restrict access to a specific file, add the following code block and edit the file name, “secretfile.jpg”, with the name of the file that you wish to protect:

# prevent viewing of a specific file
<files secretfile.jpg>
 order allow,deny
 deny from all
</files>

Prevent acess to multiple file types

To restrict access to a variety of file types, add the following code block and edit the file types within parentheses to match the extensions of any files that you wish to protect:

<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

Prevent Unauthorized Directory Browsing

Prevent unauthorized directory browsing by instructing the server to serve a “xxx Forbidden - Authorization Required” message for any request to view a directory. For example, if your site is missing it’s default index page, everything within the root of your site will be accessible to all visitors. To prevent this, include the following htaccess rule:

# disable directory browsing
Options All -Indexes

Conversely, to enable directory browsing, use the following directive:

# enable directory browsing
Options All +Indexes

Likewise, this rule will prevent the server from listing directory contents:

# prevent folder listing
IndexIgnore *

And, finally, the IndexIgnore directive may be used to prevent the display of select file types:

# prevent display of select file types
IndexIgnore *.wmv *.mp4 *.avi *.etc

Change Default Index Page

This rule tells the server to search for and serve “business.html” as the default directory index. This rule must exist in the htaccess files of the root directory for which you wish to replace the default index file (e.g., “index.html”):

# serve alternate default index page
DirectoryIndex business.html

This rule is similar, only in this case, the server will scan the root directory for the listed files and serve the first match it encounters. The list is read from left to right:

# serve first available alternate default index page from series
DirectoryIndex filename.html index.cgi index.pl default.htm

Disguise Script Extensions

To enhance security, disguise scripting languages by replacing actual script extensions with dummy extensions of your choosing. For example, to change the “.foo” extension to “.php”, add the following line to your htaccess file and rename all affected files accordingly:

# serve foo files as php files
AddType application/x-httpd-php .foo

# serve foo files as cgi files
AddType application/x-httpd-cgi .foo

Limit Access to the Local Area Network (LAN)

# limit access to local area network
<Limit GET POST PUT>
 order deny,allow
 deny from all
 allow from 192.168.0.0/33
</Limit>

Secure Directories by IP Address and/or Domain

In the following example, all IP addresses are allowed access except for 12.345.67.890 and domain.com:

# allow all except those indicated here
<Limit GET POST PUT>
 order allow,deny
 allow from all
 deny from 12.345.67.890
 deny from .*domain\.com.*
</Limit>

In the following example, all IP addresses are denied access except for 12.345.67.890 and domain.com:

# deny all except those indicated here
<Limit GET POST PUT>
 order deny,allow
 deny from all
 allow from 12.345.67.890
 allow from .*domain\.com.*
</Limit>

This is how to block unwanted visitors based on the referring domain. You can also save bandwidth by blocking specific file types — such as .jpg, .zip, .mp3, .mpg — from specific referring domains. Simply replace “scumbag” and “wormhole” with the offending domains of your choice:

# block visitors referred from indicated domains
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER} scumbag\.com [NC,OR]
 RewriteCond %{HTTP_REFERER} wormhole\.com [NC,OR]
 RewriteRule .* - [F]
</ifModule>

Prevent or allow domain access for a specified range of IP addresses

There are several effective ways to block a range of IP addresses via htaccess. This first method blocks an IP range specified by thier CIDR (Classless Inter-Domain Routing) number. This method is useful for blocking mega-spammers such as RIPE, Optinet, and others. If, for example, you find yourself adding line after line of Apache deny directives for addresses beginning with the same first few numbers, choose one of them and try a whois lookup. Listed within the whois results will be the CIDR value representing every IP address associated with that particular network. Thus, blocking via CIDR is an effective way to eloquently prevent all IP instances of the offender from accessing your site. Here is a generalized example for blocking by CIDR (edit values to suit your needs):

# block IP range by CIDR number
<Limit GET POST PUT>
 order allow,deny
 allow from all
 deny from 10.1.0.0/16
 deny from 80.0.0/8
</Limit>

Likewise, to allow an IP range by CIDR number:

# allow IP range by CIDR number
<Limit GET POST PUT>
 order deny,allow
 deny from all
 allow from 10.1.0.0/16
 allow from 80.0.0/8
</Limit>

Another effective way to block an entire range of IP addresses involves truncating digits until the desired range is represented. As an IP address is read from left to right, its value represents an increasingly specific address. For example, a fictitious IP address of 99.88.77.66 would designate some uniquely specific IP address. Now, if we remove the last two digits (66) from the address, it would represent any address beginning with the remaining digits. That is, 99.88.77 represents 99.88.77.1, 99.88.77.2, … 99.88.77.99, …etc. Likewise, if we then remove another pair of digits from the address, its range suddenly widens to represent every IP address 99.88.x.y, where x and y represent any valid set of IP address values (i.e., you would block 256*256 = 65,536 unique IP addresses). Following this logic, it is possible to block an entire range of IP addresses to varying degrees of specificity. Here are few generalized lines exemplifying proper htaccess syntax (edit values to suit your needs):

# block IP range by address truncation
<Limit GET POST PUT>
 order allow,deny
 allow from all
 deny from 99.88.77.66
 deny from 99.88.77.*
 deny from 99.88.*.*
 deny from 99.*.*.*
</Limit>

Likewise, to allow an IP range by address truncation:

# allow IP range by address truncation
<Limit GET POST PUT>
 order deny,allow
 deny from all
 allow from 99.88.77.66
 allow from 99.88.77.*
 allow from 99.88.*.*
 allow from 99.*.*.*
</Limit>

Block or allow multiple IP addresses on one line

Save a little space by blocking multiple IP addresses or ranges on one line. Here are few examples (edit values to suit your needs):

# block two unique IP addresses
deny from 99.88.77.66 11.22.33.44
# block three ranges of IP addresses
deny from 99.88 99.88.77 11.22.33

Likewise, to allow multiple IP addresses or ranges on one line:

# allow two unique IP addresses
allow from 99.88.77.66 11.22.33.44
# allow three ranges of IP addresses
allow from 99.88 99.88.77 11.22.33

Miscellaneous rules for blocking and allowing IP addresses

Here are few miscellaneous rules for blocking various types of IP addresses. These rules may be adapted to allow the specified IP values by simply changing the deny directive to allow. Check ’em out (edit values to suit your needs):

# block a partial domain via network/netmask values
deny from 99.1.0.0/255.255.0.0

# block a single domain
deny from 99.88.77.66

# block domain.com but allow sub.domain.com
order deny,allow
deny from domain.com
allow from sub.domain.com

Stop Hotlinking, Serve Alternate Content

To serve ‘em some unexpected alternate content when hotlinking is detected, employ the following code, which will protect all files of the types included in the last line (add more types as needed). Remember to replace the dummy path names with real ones. Also, the name of the nasty image being served in this case is “eatme.jpe”, as indicated in the line containing the RewriteRule. Please advise that this method will also block services such as FeedBurner from accessing your images.

# stop hotlinking and serve alternate content
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER} !^$
 RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.com/.*$ [NC]
 RewriteRule .*\.(gif|jpg)$ http://www.domain.com/eatme.jpe [R,NC,L]
</ifModule>

Note: To deliver a standard (or custom, if configured) error page instead of some nasty image of the Fonz, replace the line containing the RewriteRule in the above htaccess directive with the following line:

# serve a standard 403 forbidden error page
RewriteRule .*\.(gif|jpg)$ - [F,L]

Note: To grant linking permission to a site other than yours, insert this code block after the line containing the “domain.com” string. Remember to replace “goodsite.com” with the actual site domain:

# allow linking from the following site
RewriteCond %{HTTP_REFERER} !^http://(www\.)?goodsite\.com/.*$ [NC]

Block Evil Robots, Site Rippers, and Offline Browsers

Eliminate some of the unwanted scum from your userspace by injecting this handy block of code. After such, any listed agents will be denied access and receive an error message instead. Please advise that there are much more comprehensive lists available this example has been truncated for business purposes. Note: DO NOT include the “[OR]” on the very last RewriteCond or your server will crash, delivering “500 Errors” to all page requests.

# deny access to evil robots site rippers offline browsers and other nasty scum
RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^Anarchie [OR]
RewriteCond %{HTTP_USER_AGENT} ^ASPSeek [OR]
RewriteCond %{HTTP_USER_AGENT} ^attach [OR]
RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xenu [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus.*Webster [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* - [F,L]

Or, instead of delivering a friendly error message (i.e., the last line), send these bad boys to the hellish website of your choice by replacing the RewriteRule in the last line with one of the following two examples:

# send em to a hellish website of your choice
RewriteRule ^.*$ http://www.hellish-website.com [R,L]

Or, to send em to a virtual blackhole of fake email addresses:

# send em to a virtual blackhole of fake email addresses
RewriteRule ^.*$ http://english-61925045732.spampoison.com [R,L]

You may also include specific referrers to your blacklist by using HTTP_REFERER. Here, we use the infamously scummy domain, “iaea.org” as our blocked example, and we use “yourdomain” as your domain (the domain to which you are blocking iaea.org):

RewriteCond %{HTTP_REFERER} ^http://www.iaea.org$
RewriteRule !^http://[^/.]\.yourdomain\.com.* - [F,L]

More Stupid Blocking Tricks

Note: Although these redirect techniques are aimed at blocking and redirecting nasty scumsites, the directives may also be employed for friendly redirection purposes:

# redirect any request for anything from spamsite to differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]
RewriteRule .* http://www.differentspamsite.com [R]

# redirect all requests from spamsite to an image of something at differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]
RewriteRule .* http://www.differentspamsite/something.jpg [R]

# redirect traffic from a certain address or range of addresses to another site
RewriteCond %{REMOTE_ADDR} 192.168.10.*
RewriteRule .* http://www.differentspamsite.com/index.html [R]

Even More Scum-Blocking Tricks

Here is a step-by-step series of code blocks that should equip you with enough knowledge to block any/all necessary entities. Read through the set of code blocks, observe the patterns, and then copy, combine and customize to suit your specific scum-blocking needs:

# set variables for user agents and referers and ip addresses
SetEnvIfNoCase User-Agent ".*(user-agent-you-want-to-block|php/perl).*" BlockedAgent
SetEnvIfNoCase Referer ".*(block-this-referrer|and-this-referrer|and-this-referrer).*" BlockedReferer
SetEnvIfNoCase REMOTE_ADDR ".*(666.666.66.0|22.22.22.222|999.999.99.999).*" BlockedAddress

# set variable for any class B network coming from a given netblock
SetEnvIfNoCase REMOTE_ADDR "66.154.*" BlockedAddress

# set variable for two class B networks 198.25.0.0 and 198.26.0.0
SetEnvIfNoCase REMOTE_ADDR "198.2(5|6)\..*" BlockedAddress

# deny any matches from above and send a 403 denied
<Limit GET POST PUT>
 order deny,allow
 deny from env=BlockedAgent
 deny from env=BlockedReferer
 deny from env=BlockedAddress
 allow from all
</Limit>

Password-Protect Directories

Here is an excellent online tool for generating the necessary elements for a password-protected directory:

# password protect directories
htaccess Password Generator

Password-protect Files, Directories, and More..

Secure site contents by requiring user authentication for specified files and/or directories. The first example shows how to password-protect any single file type that is present beneath the directory which houses the htaccess rule. The second rule employs the FilesMatch directive to protect any/all files which match any of the specified character strings. The third rule demonstrates how to protect an entire directory. The fourth set of rules provides password-protection for all IP’s except those specified. Remember to edit these rules according to your specific needs.

# password-protect single file
<Files secure.php>
AuthType Basic
AuthName "Prompt"
AuthUserFile /home/path/.htpasswd
Require valid-user
</Files>

# password-protect multiple files
<FilesMatch "^(execute|index|secure|insanity|biscuit)*$">
AuthType basic
AuthName "Development"
AuthUserFile /home/path/.htpasswd
Require valid-user
</FilesMatch>

# password-protect the directory in which this htaccess rule resides
AuthType basic
AuthName "This directory is protected"
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user

# password-protect directory for every IP except the one specified
# place in htaccess file of a directory to protect that entire directory
AuthType Basic
AuthName "Personal"
AuthUserFile /home/path/.htpasswd
Require valid-user
Allow from 99.88.77.66
Satisfy Any

Require SSL (Secure Sockets Layer)

Here is an excellent method for requiring SSL (via askapache.com 3):

# require SSL
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "domain.tld"
ErrorDocument 403 https://domain.tld

# require SSL without mod_ssl
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Automatically CHMOD Various File Types

This method is great for ensuring the CHMOD settings for various file types. Employ the following rules in the root htaccess file to affect all specified file types, or place in a specific directory to affect only those files (edit file types according to your needs):

# ensure CHMOD settings for specified file types
# remember to never set CHMOD 777 unless you know what you are doing
# files requiring write access should use CHMOD 766 rather than 777
# keep specific file types private by setting their CHMOD to 400
chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600

Disguise all file extensions

This method will disguise all file types (i.e., any file extension) and present them as .php files (or whichever extension you choose):

# diguise all file extensions as php
ForceType application/x-httpd-php

Protect against denial-of-service (DOS) attacks by limiting file upload size

One method to help protect your server against DOS attacks involves limiting the maximum allowable size for file uploads. Here, we are limiting file upload size to 10240000 bytes, which is equivalent to around 10 megabytes. For this rule, file sizes are expressed in bytes. Check here for help with various file size conversions. Note: this code is only useful if you actually allow users to upload files to your site.

# protect against DOS attacks by limiting file upload size
LimitRequestBody 10240000

Secure directories by disabling execution of scripts

Prevent malicious brainiacs from actively scripting secure directories by adding the following rules to the representative htaccess file (edit file types to suit your needs):

# secure directory by disabling script execution
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI
Usability Tricks

Minimize CSS Image Flicker in IE6

Add the following htaccess rules to minimize or even eliminate CSS background-image “flickering” in MSIE6:

# minimize image flicker in IE6
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000

Deploy Custom Error Pages

Replicate the following patterns to serve your own set of custom error pages. Simply replace the “/errors/###.html” with the correct path and file name. Also change the “###” preceding the path to summon pages for other errors. Note: your custom error pages must be larger than 512 bytes in size or they will be completely ignored by Internet Explorer:

# serve custom error pages
ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html

Provide a Universal Error Document

# provide a universal error document
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /dir/error.php [L]

Employ Basic URL Spelling Check

This bit of voodoo will auto-correct simple spelling errors in the URL:

# automatically corect simple speling erors
<IfModule mod_speling.c>
 CheckSpelling On
</IfModule>

Instruct browser to download multimedia files rather than display them

Here is a useful method for delivering multimedia file downloads to your users. Typically, browsers will attempt to play or stream such files when direct links are clicked. With this method, provide a link to a multimedia file and a dialogue box will provide users the choice of saving the file or opening it. Here are a few htaccess rules demonstrating the technique (edit file types according to your specific needs):

# instruct browser to download multimedia files
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .wmv
AddType application/octet-stream .mp3

Instruct server to display source code for dynamic file types

There are many situations where site owners may wish to display the contents of a dynamic file rather than executing it as a script. To exercise this useful technique, create a directory in which to place dynamic files that should be displayed rather than executed, and add the following line of code to the htaccess file belonging to that directory. This method is known to work for .pl, .py, and .cgi file-types. Here it is:

RemoveHandler cgi-script .pl .py .cgi

Redirect visitors to a temporary site during site development

During web development, maintenance, or repair, send your visitors to an alternate site while retaining full access for yourself. This is a very useful technique for preventing visitor confusion or dismay during those awkward, web-development moments. Here are the generalized htaccess rules to do it (edit values to suit your needs):

# redirect all visitors to alternate site but retain full access for you
ErrorDocument 403 http://www.alternate-site.com
Order deny,allow
Deny from all
Allow from 99.88.77.66

Provide a password prompt for visitors during site development

Here is another possible solution for "hiding" your site during those private, site-under-construction moments. Here we are instructing Apache to provide visitors with a password prompt while providing open access to any specifically indicated IP addresses or URL’s. Edit the following code according to your IP address and other development requirements (thanks to Caleb at askapache.com for sharing this trick 3):

# password prompt for visitors
AuthType basic
AuthName "This site is currently under construction"
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user
# allow webmaster and any others open access
Order Deny,Allow
Deny from all
Allow from 111.222.33.4
Allow from favorite.validation/services/
Allow from googlebot.com
Satisfy Any

Prevent file or directory access according to specified time periods

Prevent viewing of all pictures of Fonzi during the midnight hour — or any files during any time period — by using this handy htaccess ruleset:

# prevent access during the midnight hour
RewriteCond %{TIME_HOUR} ^12$
RewriteRule ^.*$ - [F,L]

# prevent access throughout the afternoon
RewriteCond %{TIME_HOUR} ^(12|13|14|15)$
RewriteRule ^.*$ - [F,L]
Redirect Tricks

Important Note About Redirecting via mod_rewrite

For all redirects using the mod_rewrite directive, it is necessary to have the RewriteEngine enabled. It is common practice to enable the mod_rewrite directive in either the server configuration file or at the top of the site’s root htaccess file. If the mod_rewrite directive is not included in either of these two places, it should be included as the first line in any code block that utilizes a rewrite function (i.e., mod_rewrite), but only needs to be included once for each htaccess file. The proper mod_rewrite directive is included here for your convenience, but may or may not also be included within some of the code blocks provided in this article:

# initialize and enable rewrite engine
RewriteEngine on

Redirect from http://www.domain.com to http://domain.com

This method uses a “301 redirect” to establish a permanent redirect from the “www-version” of a domain to its respectively corresponding “non-www version”. Be sure to test immediately after preparing 301 redirects and remove it immediately if any errors occur. Use a “server header checker” to confirm a positive 301 response. Further, always include a trailing slash “/” when linking directories. Finally, be consistent with the “www” in all links (either use it always or never).

# permanently redirect from www domain to non-www domain
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]

Redirect from http://old-domain.com to http://new-domain.com

For a basic domain change from “old-domain.com” to “new-domain.com” (and folder/file names have not been changed), use the Rewrite rule to remap the old domain to the new domain. When checking the redirect live, the old domain may appear in the browser’s address bar. Simply check an image path (right-click an image and select “properties”) to verify proper redirection. Remember to check your site thoroughly after implementing this redirect.

# redirect from old domain to new domain
RewriteEngine On
RewriteRule ^(.*)$ http://www.new-domain.com/$1 [R=301,L]

Redirect String Variations to a Specific Address

For example, if we wanted to redirect any requests containing the character string, “perish”, to our main page at http://perishablepress.com/, we would replace “some-string” with “perish” in the following code block:

# redirect any variations of a specific character string to a specific address
RewriteRule ^some-string http://www.domain.com/index.php/blog/target [R]

Here are two other methods for accomplishing string-related mapping tasks:

# map URL variations to the same directory on the same server
AliasMatch ^/director(y|ies) /www/docs/target

# map URL variations to the same directory on a different server
RedirectMatch ^/[dD]irector(y|ies) http://domain.com

Other Fantastic Redirect Tricks

Redirect an entire site via 301:

# redirect an entire site via 301
redirect 301 / http://www.domain.com/

Redirect a specific file via 301:

# redirect a specific file via 301
redirect 301 /current/currentfile.html http://www.newdomain.com/new/newfile.html

Redirect an entire site via permanent redirect:

# redirect an entire site via permanent redirect
Redirect permanent / http://www.domain.com/

Redirect a page or directory via permanent redirect:

# redirect a page or directory
Redirect permanent old_file.html http://www.new-domain.com/new_file.html
Redirect permanent /old_directory/ http://www.new-domain.com/new_directory/

Redirect a file using RedirectMatch:

# redirect a file using RedirectMatch
RedirectMatch 301 ^.*$ http://www.domain.com/index.html

Note: When redirecting specific files, use Apache‘s Redirect rule for files within the same domain. Use Apache‘s RewriteRule for any domains, especially if they are different. The RewriteRule is more powerful than the Redirect rule, and thus should serve you more effectively.

Thus, use the following for a stronger, harder page redirection (first line redirects a file, second line a directory, and third a domain):

# redirect files directories and domains via RewriteRule
RewriteRule http://old-domain.com/old-file.html http://new-domain.com/new-file.html
RewriteRule http://old-domain.com/old-dir/ http://new-domain.com/new-dir/
RewriteRule http://old-domain.com/ http://new-domain.com/

Send visitors to a subdomain

This rule will ensure that all visitors are viewing pages via the subdomain of your choice. Edit the "subdomain", "domain", and "tld" to match your subdomain, domain, and top-level domain respectively:

# send visitors to a subdomain
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$ [NC]
RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]

More fun with RewriteCond and RewriteRule

# rewrite only if the file is not found
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)special\.html?$ cgi-bin/special/special-html/$1

# rewrite only if an image is not found
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule images/special/(.*).gif cgi-bin/special/mkgif?$1

# seo-friendly rewrite rules for various directories
RewriteRule ^(.*)/aud/(.*)$ $1/audio-files/$2 [L,R=301]
RewriteRule ^(.*)/img/(.*)$ $1/image-files/$2 [L,R=301]
RewriteRule ^(.*)/fla/(.*)$ $1/flash-files/$2 [L,R=301]
RewriteRule ^(.*)/vid/(.*)$ $1/video-files/$2 [L,R=301]

# broswer sniffing via htaccess environmental variables
RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
RewriteRule ^/$ /index-for-mozilla.html [L]
RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
RewriteRule ^/$ /index-for-lynx.html [L]
RewriteRule ^/$ /index-for-all-others.html [L]

# redirect query to Google search
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_URI} .google\.php*
RewriteRule ^(.*)$ ^http://www.google.com/search?q=$1 [R,NC,L]

# deny request according to the request method
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)$ [NC]
RewriteRule ^.*$ - [F]

# redirect uploads to a better place
RewriteCond %{REQUEST_METHOD} ^(PUT|POST)$ [NC]
RewriteRule ^(.*)$ /cgi-bin/upload-processor.cgi?p=$1 [L,QSA]

More fun with Redirect 301 and RedirectMatch 301

# seo friendly redirect for a single file
Redirect 301 /old-dir/old-file.html http://domain.com/new-dir/new-file.html

# seo friendly redirect for multiple files
# redirects all files in dir directory with first letters xyz
RedirectMatch 301 /dir/xyz(.*) http://domain.com/$1

# seo friendly redirect entire site to a different domain
Redirect 301 / http://different-domain.com
WordPress Tricks

Secure WordPress Contact Forms

Protect your insecure WordPress contact forms against online unrighteousness by verifying the domain from whence the form is called. Remember to replace the “domain.com” and “contact.php” with your domain and contact-form file names, respectively.

# secure wordpress contact forms via referrer check
RewriteCond %{HTTP_REFERER} !^http://www.domain.com/.*$ [NC]
RewriteCond %{REQUEST_POST} .*contact.php$
RewriteRule .* - [F]

WordPress Permalinks

In our article, The htaccess rules for all WordPress Permalinks, we revealed the precise htaccess directives used by the WordPress blogging platform for permalink functionality. Here, for the sake of completeness, we repeat the directives only. For more details please refer to the original article:

If WordPress is installed in the site’s root directory, WordPress creates and uses the following htaccess directives:

# BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>
# END WordPress

If WordPress is installed in some subdirectory “foo”, WordPress creates and uses the following htaccess directives:

# BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /foo/
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /foo/index.php [L]
</IfModule>
# END WordPress
Random Tricks

Activate SSI for HTML/SHTML file types:

# activate SSI for HTML and or SHTML file types
AddType text/html .html
AddType text/html .shtml
AddHandler server-parsed .html
AddHandler server-parsed .shtml
AddHandler server-parsed .htm

Grant CGI access in a specific directory:

# grant CGI access in a specific directory
Options +ExecCGI
AddHandler cgi-script cgi pl
# to enable all scripts in a directory use the following
SetHandler cgi-script

Disable magic_quotes_gpc for PHP enabled servers:

# turn off magic_quotes_gpc for PHP enabled servers
<ifmodule mod_php4.c>
 php_flag magic_quotes_gpc off
</ifmodule>

Enable MD5 digests:

Note: enabling this option may result in a relative decrease in server performance.

# enable MD5 digests via ContentDigest
ContentDigest On

Expression Engine Tricks:

# send Atom and RSS requests to the site docroot to be rewritten for ExpressionEngine
RewriteRule .*atom.xml$ http://www.yoursite.com/index.php/weblog/rss_atom/ [R]
RewriteRule .*rss.xml$ http://www.yoursite.com/index.php/weblog/rss_2.0/ [R]

# cause all requests for index.html to be rewritten for ExpressionEngine
RewriteRule /.*index.html$ http://www.domain.com/index.php [R]

 8 
 -: December 23, 2008, 12:29:47 am 
Започната от ron - Последна публикация от ron
Код:
mysql -uusername -ppassword database -e 'show table status;' | awk '{sum=sum+$7+$9;} END {print sum/1024/1024}'

 9 
 -: December 09, 2008, 07:36:43 pm 
Започната от ron - Последна публикация от ron
Код:
#!/bin/bash
# Shell script to restart MySQL server if it is killed or not working
# due to ANY causes.
# When script detects mysql is not running (it basically sends ping request
# to MySQL) it try to start using /etc/init.d/mysql script; and it sends an
# email to user indicating the status.
# This script must be run from Cron Job so that it can monitor mysql server.
 
# mysql root/admin username
MUSER="root"
# mysql admin/root password
MPASS="SET-ROOT-PASSWORD"
# mysql server hostname
MHOST="localhost"
#Shell script to start MySQL server i.e. path to MySQL daemon start/stop script.
# Debain uses following script, need to setup this according to your UNIX/Linux/BSD OS.
MSTART="/etc/init.d/mysql start"
# Email ID to send notification
EMAILID="notification@somewhere-corp.com"
# path to mail program
MAILCMD="$(which mail)"
# path mysqladmin
MADMIN="$(which mysqladmin)"
 
#### DO NOT CHANGE anything BELOW ####
MAILMESSAGE="/tmp/mysql.fail.$$"
 
# see if MySQL server is alive or not
# 2&1 could be better but i would like to keep it simple and easy to
# understand stuff :)
$MADMIN -h $MHOST -u $MUSER -p${MPASS} ping 2>/dev/null 1>/dev/null
if [ $? -ne 0 ]; then
echo "" >$MAILMESSAGE
echo "Error: MySQL Server is not running/responding ping request">>$MAILMESSAGE
echo "Hostname: $(hostname)" >>$MAILMESSAGE
echo "Date & Time: $(date)" >>$MAILMESSAGE
# try to start mysql
$MSTART>/dev/null
# see if it is started or not
o=$(ps cax | grep -c ' mysqld$')
if [ $o -eq 1 ]; then
sMess="MySQL Server MySQL server successfully restarted"
else
sMess="MySQL server FAILED to restart"
fi
# Email status too
echo "Current Status: $sMess" >>$MAILMESSAGE
echo "" >>$MAILMESSAGE
echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE
echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE
# send email
$MAILCMD -s "MySQL server" $EMAILID < $MAILMESSAGE
else # MySQL is running :) and do nothing
:
fi
# remove file
rm -f $MAILMESSAGE

 10 
 -: December 09, 2008, 07:19:46 pm 
Започната от ron - Последна публикация от ron
За да правите backup на всички бази данни в определена директория, можете да използвате следния скрипт.
Той позволява и пропускането на някои бази данни

Код:
#!/bin/bash
# Shell script to backup MySql database
# To backup Nysql databases file to /backup dir and later pick up by your
# script. You can skip few databases from backup too.
 
MyUSER="SET-MYSQL-USER-NAME"     # USERNAME
MyPASS="SET-PASSWORD"       # PASSWORD
MyHOST="localhost"          # Hostname
 
# Linux bin paths, change this if it can't be autodetected via which command
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
CHOWN="$(which chown)"
CHMOD="$(which chmod)"
GZIP="$(which gzip)"
 
# Backup Dest directory, change this if you have someother location
DEST="/backup"
 
# Main directory where backup will be stored
MBD="$DEST/mysql"
 
# Get hostname
HOST="$(hostname)"
 
# Get data in dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y")"
 
# File to store current backup file
FILE=""
# Store list of databases
DBS=""
 
# DO NOT BACKUP these databases
IGGY="test"
 
[ ! -d $MBD ] && mkdir -p $MBD || :
 
# Only root can access it!
$CHOWN 0.0 -R $DEST
$CHMOD 0600 $DEST
 
# Get all database list first
DBS="$($MYSQL -u $MyUSER -h $MyHOST -p$MyPASS -Bse 'show databases')"
 
for db in $DBS
do
    skipdb=-1
    if [ "$IGGY" != "" ];
    then
for i in $IGGY
do
    [ "$db" == "$i" ] && skipdb=1 || :
done
    fi
 
    if [ "$skipdb" == "-1" ] ; then
FILE="$MBD/$db.$HOST.$NOW.gz"
# do all inone job in pipe,
# connect to mysql using mysqldump for select mysql database
# and pipe it out to gz file in backup dir :)
        $MYSQLDUMP -u $MyUSER -h $MyHOST -p$MyPASS $db | $GZIP -9 > $FILE
    fi
done

Страници: [1] 2