Как разрешить обновить страницу только один раз

Here is a small piece of code that allows to reload a page only once. This is necessary to prevent some data being cached and this is the only solution I found good for my needs. Meta tag nocache did not save me, and meta tag refresh does not allow to refresh the page only once. So here is the code:

<script>
var reloaded = false;
var loc=””+document.location;
loc = loc.indexOf(”?reloaded=”)!=-1?loc.substring(loc.indexOf(”?reloaded=”)+10,loc.length):””;
loc = loc.indexOf(”&”)!=-1?loc.substring(0,loc.indexOf(”&”)):loc;
reloaded = loc!=””?(loc==”true”):reloaded;

function reloadOnceOnly() {
if (!reloaded)
window.location.replace(window.location+”?reloaded=true”);
}
reloadOnceOnly();
</script>

I found this in Google, but I had to spend some hours before I did it. So I think this article will be helpful for you.

Перенаправление трафика через .htaccess без параметров в адресной строке

Бывают случаи, когда нужно перенаправить весь трафик с одного сайта на другой. Однако структура сайтов различна и необходимо перенаправить посетителей с www.site-1.com на главную страницу www.site-2.com, но при этом не передавать параметры запроса в адресной строке.
Например, посетитель пришел по ссылке www.site-1.com/index.php?f=12&as=23 при этом редирект установлен на www.site-2.com. При обычном перенаправлении, параметр f=12&as=23 так же будет передан.
Чтобы этого избежать, необходимо создать два файла в корне site-1.com.
файл .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ http://www.site-1.com/redirect.php


Данные директивы указывают перенаправлять весь трафик на php-скрипт redirect.php
Создадим файл redirect.php и напишем внутри:
<?php
header ("Location: http://www.site-2.com");
?>

В результате мы получаем “чистый” редирект с site-1.com на site-2.com без параметров в запросе

Exim + greylist

I want to share how i reduce spam in my box.

Maybe not perfect solution but  works 🙂
Always make backup and use it at your own risk !

Tested on CentOS 5

Install Greylist:

# rpm -Uvh http://dl.atrpms.net/el5-i386/atrpms/stable/greylistd-0.8.3.2-8.0.el5.noarch.rpm

Now you need to change permissions:

# chown -R mail.mail /etc/greylistd/
# chown -R mail.mail /var/run/greylistd/
# chown -R mail.mail /var/lib/greylistd/
# chown -R mail.mail /usr/sbin/greylist*

start greylistd:

# /usr/bin/su mail -c /usr/sbin/greylistd &

I use original SpamBlocker2 (thanks to Jeff )

######################################################################
# SpamBlocker.exim.conf.2.1.1-release                                #
# 05-Jun-2007                                                        #
# Runtime configuration file for DirectAdmin/Exim 4.24 and above     #
# Requires exim.pl dated 20-Apr-2007 17:09 or later                  #

You will need to edit /etc/exim.conf
Add

acl_smtp_connect = acl_connect
acl_smtp_helo = check_helo

just before:

acl_smtp_rcpt = check_recipient
acl_smtp_data = check_message

Find

######################################################################
# ACLs #
######################################################################
begin acl

add after:

###############################
# ACL connect
###############################
acl_connect:
accept hosts = +whitelist_hosts_ip : +relay_hostsdrop message = Your IP Blacklisted - see http://www.domain.com/
hosts = +bad_sender_hosts_ip

# We do not receive mails from orange, hinet... etc
drop message = Sender Blacklisted - http://www.yourdomain.tld/blocked.html?$sender_host_name
condition = ${if match{$sender_host_name} \
{hinet-ip|hinet|orange|asianet.co.th} \
{yes}{no}}

# Delay. (Spammers doesn&#039;t like to wait while connecting
# Better do not use on high load servers because it will hold too many open connection
# to 587 port accept connection without delay
accept condition = ${if eq {$interface_port}{587}{yes}{no}}

accept
logwrite = Delay 10s for $sender_host_address ($sender_host_name)
delay = 10s

###############################
# ACL HELO/EHLO
###############################
check_helo:

accept condition = ${if eq {$interface_port}{587}{yes}{no}}
accept hosts = +whitelist_hosts: +whitelist_hosts_ip : +relay_hosts

# for some cases this rule may need to comment
deny message = rejected due to forged HELO name - $sender_helo_name
condition = ${if match {$sender_helo_name} \
{\N^[^.].*\.[^.]+$\N} \
{no}{yes}}
!hosts = +whitelist_hosts: +whitelist_hosts_ip : +relay_hosts

drop message = HELO/EHLO cannot be numbers only
condition = ${if match{$sender_helo_name}{\N^\d+$\N}{yes}{no}}

# If remote host greets with an IP address, reject connection:
drop message = IP address not allowed in HELO/EHLO
condition = ${if isip {$sender_helo_name}{true}{false}}

drop message = This is my IP. Go away
condition = ${if eq{$sender_helo_name}{$interface_address} {yes}{no}}

deny message = HELO/EHLO required by SMTP RFC.
condition = ${if eq{$sender_helo_name}{}{yes}{no}}

accept

Find:

#require verify = sender

Add after:

drop message = Use your provider SMTP. Email blocked
condition = ${if match{$sender_host_name} \
{adsl|dialup|pool|peer|dhcp|dsl|broadband|ppp|dynamic|cable} \
{yes}{no}}
hosts = !+relay_hosts
domains = +use_rbl_domains
!authenticated = *

find:

# accept if address is in a local domain as long as recipient can be verified
accept domains = +local_domains
endpass
message = "Unknown User"

Add before:

# Perform greylisting.
defer message = $sender_host_address is greylisted. Please try again later.
log_message = greylisted.
domains = +relay_domains : +local_domains
!senders = : postmaster@*
!hosts = : +relay_hosts : \
${if exists {/etc/greylistd/whitelist-hosts}\
{/etc/greylistd/whitelist-hosts}{}} : \
${if exists {/etc/virtual/whitelist-hosts}\
{/etc/virtual/whitelist-hosts}{}}verify = recipient/callout=5s,use_sender,defer_ok
condition = ${readsocket{/var/run/greylistd/socket}\
{--grey $sender_host_address $sender_address $local_part@$domain}{5s}{}{false}}

Save exim.conf and restart exim:
# service exim restart

That’s All.
Now you can check maillog and see something like below :

2008-03-17 09:20:03 H=(pentium) [84.21.226.22] rejected EHLO or HELO pentium: rejected due to forged HELO name - pentium
2008-03-17 12:22:28 Delay 10s for 59.93.211.220 ()
2008-03-17 12:22:35 H=(59.94.122.15) [59.94.122.15] rejected EHLO or HELO 59.94.122.15: IP address not allowed in HELO/EHLO
2008-03-17 12:22:52 H=cpc1-neww3-0-0-cust845.cdif.cable.ntl.com (home-ad73427dc5) [82.11.227.78] F= rejected RCPT : Use your provider SMTP. Email blocked
2008-03-17 12:28:23 H=n4a.bullet.mail.ac4.yahoo.com [76.13.13.67] rejected connection in "connect" ACL: Sender Blacklisted
2008-03-17 13:05:17 H=hore.iptelecom.net.ua [212.xx.224.8] F=<ins> temporarily rejected RCPT : greylisted.<code>2008-03-17 13:09:48 H=ppp85-140-xx-38.pppoe.mtu-net.ru (mtu-net.ru) [85.140.xx.38] F= rejected RCPT : Use your provider SMTP. Email blocked

Also you can check greylisting stats:

# greylist stats
Statistics since Sun Mar 16 23:18:21 2008 (14 hours and 53 minutes ago)
-----------------------------------------------------------------------
146 items, matching 171 requests, are currently whitelisted
0 items, matching 0 requests, are currently blacklisted
155 items, matching 156 requests, are currently greylistedOf 146 items that were initially greylisted:
- 146 (100.0%) became whitelisted
- 0 ( 0.0%) expired from the greylist
-----------------------------------------------------------------------

I hope this small How-To will help you to reduce incoming spam.

CSF Firewall

CSF Firewall от ConfigServer

updated: 19.02.2009

Достаточно продвинутый скрипт. Имеет множество функций и работает практически под всеми версиями linux (RedHat/CentOS/Fedora, OpenSUSE, Debian/Ubuntu,Mandriva 2009)

Возможности:

  • Straight-forward SPI iptables firewall script
  • Daemon process that checks for login authentication failures for:
    • Courier imap, Dovecot, uw-imap, Kerio
    • openSSH
    • cPanel, WHM, Webmail (cPanel servers only)
    • Pure-pftd, vsftpd, Proftpd
    • Password protected web pages (htpasswd)
    • Mod_security failures (v1 and v2)
    • Suhosin failures
    • Exim SMTP AUTH
    • Custom login failures with separate log file and regular expression matching
  • POP3/IMAP login tracking to enforce logins per hour
  • SSH login notification
  • SU login notification
  • Excessive connection blocking
  • UI Integration for cPanel, DirectAdmin and Webmin
  • Easy upgrade between versions from within cPAnel/WHM, DirectAdmin or Webmin
  • Easy upgrade between versions from shell
  • Pre-configured to work on a cPanel server with all the standard cPanel ports open
  • Pre-configured to work on a DirectAdmin server with all the standard DirectAdmin ports open
  • Auto-configures the SSH port if it’s non-standard on installation
  • Block traffic on unused server IP addresses – helps reduce the risk to your server
  • Alert when end-user scripts sending excessive emails per hour – for identifying spamming scripts
  • Suspicious process reporting – reports potential exploits running on the server
  • Excessive user processes reporting
  • Excessive user process usage reporting and optional termination
  • Suspicious file reporting – reports potential exploit files in /tmp and similar directories
  • Directory and file watching – reports if a watched directory or a file changes
  • Block traffic on the DShield Block List and the Spamhaus DROP List
  • BOGON packet protection
  • Pre-configured settings for Low, Medium or High firewall security (cPanel servers only)
  • Works with multiple ethernet devices
  • Server Security Check – Performs a basic security and settings check on the server (via cPanel/DirectAdmin/Webmin UI)
  • Allow Dynamic DNS IP addresses – always allow your IP address even if it changes whenever you connect to the internet
  • Alert sent if server load average remains high for a specified length of time
  • mod_security log reporting (if installed)
  • Email relay tracking – tracks all email sent through the server and issues alerts for excessive usage (cPanel servers only)
  • IDS (Intrusion Detection System) – the last line of detection alerts you to changes to system and application binaries
  • SYN Flood protection
  • Ping of death protection
  • Port Scan tracking and blocking
  • Permanent and Temporary (with TTL) IP blocking
  • Exploit checks
  • Account modification tracking – sends alerts if an account entry is modified, e.g. if the password is changed or the login shell
  • Shared syslog aware
  • Передустановкой следует удалить скрипты APF+BFD, если они используются.

    Установка проста: скачиваем последний архив, распаковываем и запускаем файл install.sh

    wget http://www.configserver.com/free/csf.tgz
    tar -xzf csf.tgz
    cd csf
    sh install.sh

    После установки следует поправить конфиг фаирвола “под себя”.

    …. продолжение следует ….

APF (Advanced Policy Firewall)

Достаточно известный firewall под названием APF (Advanced Policy Firewall)
APF – надстройка над iptables и распространяется по лицензии GNU GENERAL PUBLIC LICENSE.
Уверенно работает на следующих ОС:
Redhat Enterprise AS/ES 2+
CentOS Any
Fedora Core Any
Slackware 8.0+
Debian GNU/Linux 3.0+
Suse Linux 8.1+
Unbuntu Any
TurboLinux Server 9+
TurboLinux Fuji (Desktop)
RedHat Linux 7.3,8,9

APF достаточно прост в установке и использовании.
Итак:

# wget http://www.r-fx.ca/downloads/apf-current.tar.gz
# tar -xvf ./apf-current.tar.gz
# cd apf-9.6-5
# ./install.sh
Installing APF 9.6-5: Completed.

Installation Details:
Install path: /etc/apf/
Config path: /etc/apf/conf.apf
Executable path: /usr/local/sbin/apf

Далее, в конфигурационном файле /etc/apf/apf.conf необходимо сделать некоторые правки.
Каждый параметр в конфигурационном файле достаточно подробно расписан и разобраться за что он отвечает, думаю, не составит особого труда.
Некоторые моменты:
DEVEL_MODE=”1″
включается для проверки работоспособности фаирвола. Если все настроено правильно, данный параметр нужно установить в “0”, иначе фаирвол будет остановлен через 5 минут после старта.

Описываем входящие порты:
IG_TCP_CPORTS=”20,21,25,53,80,110,143,443,587,2222,465,993,995″
# 2222 – для панели directAdmin
# 587 – дополнительный smtp порт для exim-a

Описываем исходящие порты:
EG_TCP_CPORTS=”21,25,80,443,43,35000_35999″
# 35000_35999 порты для работы proftpd в пассивном режиме
# эти порты должны соответствовать тем, которые указаны в настройках proftpd

Старт:
apf -s
Остановка:
apf -f
Блокировать определённый IP адрес:
apf -d 123.123.123.123 comments
Разблокировать определённый IP адрес:
apf -u 123.123.123.123

Более подробно о командах и конфигурации описано в файле: /etc/apf/doc.README.apf

Довольно часто AFP используют совместно с BFD (Brute Force Detection)
BFD – это shell-скрипт, который сканирует логи (apache, sshd, ftp) на предмет несанкционированного доступа, подбора паролей и т.д. и при превышении заданных значений – блокирует IP с помощью APF.
Подробнее в README на сайте.

…… продолжение следует….

Способы переключения раскладки в KDE 3.x

1. Правка конфига /etc/X11/xorg.conf
Универсальный способ, работает в Kde / Gnome / Xfce / и т.д. Но есть недостаток – переключение языка действует глобально для всех окон/приложений, кроме того, нет индикатора раскладки. Однако ничто не мешает использовать какой-нибудь led 🙂

Section "InputDevice"
Identifier "Keyboard0"
Driver "kbd"
Option "XkbRules" "xorg"
Option "XkbModel" "pc105"
Option "XkbLayout" "us,ru"
Option "XkbOptions" "grp:ctrl_shift_toggle,grp_led:scroll"
Option "XkbVariant" ",winkeys"
EndSection

При использовании “grp_led:scroll” будет включаться/выключаться индикатор ScrollLock при переключении языков.
“grp:ctrl_shift_toggle” – переключения языка по Control+Shift

2. Поставить kkbswitch (aptitude install kkbswitch). Пакет берёт инфо о языках и клавишах переключения из xorg.conf. Пример для 2х языков:
Section "InputDevice"
Identifier "Keyboard0"
Driver "kbd"
Option "XkbRules" "xorg"
Option "XkbModel" "pc105"
Option "XkbLayout" "us,ru"
Option "XkbOptions" "grp:ctrl_shift_toggle"
Option "XkbVariant" ",winkeys"
EndSection

Языки переключаются по Ctrl+Shift (“grp:ctrl_shift_toggle”). Кроме того, в самом kkbswitch можно настроить “влияние” раскладки глобально или отдельно для каждого окна/приложения.

Установка драйвера nvidia-glx Debian Lenny

http://gq.net.ru/2007/05/05/installing-ati-or-nvidia-drivers-into-debian-etch/
Пакеты с драйвером и исходниками модуля (или самим модулем) взять из sid’а

Другой вариант:
http://techpatterns.com/forums/about933.html

По материалам рассылки debian-russian

Чистка меню в xfce4

> При установке программ в Wine они добавились в меню XFCE. Но после стирания
> программ и даже удаления самого Wine ссылки остались. Меню создаётся каким-то
> хуком, ручного редактирования нет.Как бы стереть эти “мёртвые души”?
> И многие программы не добавляются в меню, хотя в подменю “Debian” иногда попадают.
> Как с этим бороться?

Пункты в меню появляются если в /usr/share/applications/ есть соответственный файл обычно_имя_программы.desktop. Видимо, при удалении прграммы, вайн, создавший данный файл, не удаляет его, удали в ручную и пункты меню пропадут. Подобным же образом пункты меню можно создать.
Посмотри один из *.desktop там всё наглядно.


Murat D. Kadirov

По материалам рассылки debian-russian

Короткие “напоминалки”

* практическия вся информация собрана из рассылки nginx. Чтобы не рыться, решил собрать некоторые моменты тут, в одной куче 🙂

HTTP redirect с requested домена на какой угодно адрес (target_domain.tld)
редирект без использования location:

server {
listen IP:80;
server_name requested_domain.tld;
rewrite ^ http://target_domain.tld$request_uri;
}

редирект с использованием location:

server {
listen IP:80;
server_name requested_domain.tld;
location = / { rewrite ^ http://redirect.to/; }
}

как максимально просто запретить запросы с определенными user-agent ?
можно сделать примерно так:

if ($http_user_agent ~ AESOP_com_SpiderMan|Alexibot|Anonymouse\.org|asterias|attach|BackDoorBot|BackWeb|Bandit|Baiduspider|BatchFTP|Bigfoot)
return 503;
}

как сделать так, чтобы пользователь набрав some.site.ru и если этот some не прописан в конфиге редиректился на основной сайт, т.е. www.site.ru ?
Определить server с listen default и уже в нем делать:
rewrite (.*) http://www.site.ru/$1 permanent;

Можно ли для определённого локейшна каким-либо образом реализовать такой алгоритм: смотрим на файл, если находим его-отдаём. Если такого файла нет-запрашиваем у бэкэнда.
это одно из самых распространенных применений nginx:
http://sysoev.ru/nginx/docs/http/ngx_http_core_module.html#error_page


location / {
root /home/site1/public_html;
error_page 404 = @backend;
# если нужно поменять код ответа, укажите его после =
# error_page 404 =200 @backend;
}location @backend {
proxy_set_header
...
proxy_pass http://127.0.0.1:123;
}