Вперед Назад Содержание

5. Взаимодействие между броузерами и Squid-ом

Большинство теперешних web-броузеров поддерживают работу через прокси и очень просто настраиваются для использования сервера Squid в качестве прокси. Some browsers support advanced features such as lists of domains or URL patterns that shouldn't be fetched through the proxy, or JavaScript automatic proxy configuration.

5.1 Ручная настройка Netscape

Выберите пункт Network Preferences из меню Options. На вкладке Proxies щелкните по переключателю Manual Proxy Configuration, затем по кнопке View. Для каждого из поддерживаемых Squid-ом протокола (по умолчанию это HTTP, FTP и gopher) укажите имя хоста Squid-сервера или его IP-адрес, также укажите номер HTTP порта для вашего сервера Squid (по умолчанию - 3128) в поле Port. Для других протоколов, которые Squid не поддерживает, оставьту поля пустыми.

Гланьте screen shot окна ручной настройки прокси для Netscape Navigator.

5.2 Автоматическая настройка Netscape

Настройка прокси в Netscape Navigator может быть автоматизирована при помощи JavaScript (для версий Navigator 2.0 и выше). Выберите пункт Network Preferences из меню Options. На вкладке Proxies щелкните по переключателю Automatic Proxy Configuration, затем внесите URL для вашего JavaScript-а настройки прокси в текстовое поле. Поле достаточно мало, но текст будет подвигаться по мере того как вы достигаете правой границы.

Гляньте screen shot окна автоматической настройки прокси для Netscape Navigator.

Вы можете также прокононсультироваться с документацией по Navigator от Netscape для JavaScript-а настройки прокси

Ниже приведен простой автоконфигурационный JavaScript от Oskar Pearson:


//We (www.is.co.za) run a central cache for our customers that they
//access through a firewall - thus if they want to connect to their intranet
//system (or anything in their domain at all) they have to connect
//directly - hence all the "fiddling" to see if they are trying to connect
//to their local domain.

//Replace each occurrence of company.com with your domain name
//and if you have some kind of intranet system, make sure
//that you put it's name in place of "internal" below.

//We also assume that your cache is called "cache.company.com", and
//that it runs on port 8080. Change it down at the bottom.

//(C) Oskar Pearson and the Internet Solution (http://www.is.co.za)

    function FindProxyForURL(url, host)
        {
            //If they have only specified a hostname, go directly.
            if (isPlainHostName(host))
                    return "DIRECT";

            //These connect directly if the machine they are trying to
            //connect to starts with "intranet" - ie http://intranet
            //Connect  directly if it is intranet.*
            //If you have another machine that you want them to
            //access directly, replace "internal*" with that
            //machine's name
            if (shExpMatch( host, "intranet*")||
                            shExpMatch(host, "internal*"))
                return "DIRECT";

            //Connect directly to our domains (NB for Important News)
            if (dnsDomainIs( host,"company.com")||
            //If you have another domain that you wish to connect to
            //directly, put it in here
                            dnsDomainIs(host,"sistercompany.com"))
                return "DIRECT";

            //So the error message "no such host" will appear through the
            //normal Netscape box - less support queries :)
            if (!isResolvable(host))
                    return "DIRECT";

            //We only cache http, ftp and gopher
            if (url.substring(0, 5) == "http:" ||
                            url.substring(0, 4) == "ftp:"||
                            url.substring(0, 7) == "gopher:")

            //Change the ":8080" to the port that your cache
            //runs on, and "cache.company.com" to the machine that
            //you run the cache on
                    return "PROXY cache.company.com:8080; DIRECT";

            //We don't cache WAIS
            if (url.substring(0, 5) == "wais:")
                    return "DIRECT";

            else
                    return "DIRECT";
        }

5.3 Настройка Lynx и Mosaic

Для Mosaic и Lynx вы можете установить переменные окружения перед запуском приложения. К примеру (подразумевается использование csh или tcsh):

        % setenv http_proxy http://mycache.example.com:3128/
        % setenv gopher_proxy http://mycache.example.com:3128/
        % setenv ftp_proxy http://mycache.example.com:3128/

Для Lynx вы можете также отредактировать файл lynx.cfg, настроив использование прокси. Это даст возможность всем пользователям Lynx в системе иметь доступ к прокси без изменений переменных окружения для каждого пользователя в отдельности. К примеру:

        http_proxy:http://mycache.example.com:3128/
        ftp_proxy:http://mycache.example.com:3128/
        gopher_proxy:http://mycache.example.com:3128/

5.4 Redundant Proxy Auto-Configuration

There's one nasty side-effect to using auto-proxy scripts: if you start the web browser it will try and load the auto-proxy-script.

If your script isn't available either because the web server hosting the script is down or your workstation can't reach the web server (e.g. because you're working off-line with your notebook and just want to read a previously saved HTML-file) you'll get different errors depending on the browser you use.

The Netscape browser will just return an error after a timeout (after that it tries to find the site 'www.proxy.com' if the script you use is called 'proxy.pac').

The Microsoft Internet Explorer on the other hand won't even start, no window displays, only after about 1 minute it'll display a window asking you to go on with/without proxy configuration.

The point is that your workstations always need to locate the proxy-script. I created some extra redundancy by hosting the script on two web servers (actually Apache web servers on the proxy servers themselves) and adding the following records to my primary nameserver:

        proxy   CNAME           proxy1
                CNAME           proxy2
The clients just refer to 'http://proxy/proxy.pac'. This script looks like this:

function FindProxyForURL(url,host)
{
        // Hostname without domainname or host within our own domain?
        // Try them directly:
        // http://www.domain.com actually lives before the firewall, so
        // make an exception:
        if ((isPlainHostName(host)||dnsDomainIs( host,".domain.com")) &&
                !localHostOrDomainIs(host, "www.domain.com"))
                return "DIRECT";

        // First try proxy1 then proxy2. One server mostly caches '.com'
        // to make sure both servers are not
        // caching the same data in the normal situation. The other
        // server caches the other domains normally.
        // If one of 'm is down the client will try the other server.
        else if (shExpMatch(host, "*.com"))
                return "PROXY proxy1.domain.com:8080; PROXY proxy2.domain.com:8081; DIRECT";
        return "PROXY proxy2.domain.com:8081; PROXY proxy1.domain.com:8080; DIRECT";
}

I made sure every client domain has the appropriate 'proxy' entry. The clients are automatically configured with two nameservers using DHCP.

-- Rodney van den Oever

5.5 Proxy Auto-Configuration with URL Hashing

The Sharp Super Proxy Script page contains a lot of good information about hash-based proxy auto-configuration scripts. With these you can distribute the load between a number of caching proxies.

5.6 Настройка Microsoft Internet Explorer

Выберите пункт Options из меню View. Перейдите на вкладку Connection tab. Включите опцию Connect through Proxy Server и нажмите кнопку Proxy Settings. Для каждого типа протоколов, которые поддерживает Squid (по умолчанию это HTTP, FTP и gopher) укажите имя хоста сервера Squid или его IP-адрес, а также номер HTTP- порта сервера Squid (по умолчанию 3128), в колонке Port. Для других, неподдерживаемых протоколов, поля оставьте пустыми.

См. screen shot окна настройки прокси для Internet Explorer.

Microsoft также начал поддерживать JavaScript для автоматической настройки прокси в стиле Netscape. На сегодняшний момент только MSIE версии 3.0a для Windows 3.1 и Windows NT 3.51 поддерживает такую возможность (т.е. в версии 3.01 сборки 1225 для Windows 95 и NT 4.0 такая возможность не включена).

Если ваша версия MSIE имеет такую возможность, то выберите пункт Options из меню View. Перейдите на вкладку Advanced. Нажмите на кнопку Automatic Configuration в левом нижнем углу. Укажите URL для вашего JavaScript в поле предложеного вам диалога. Затем закроейт MSIE и запустите его снова, чтобы изменения вступили в силу. MSIE будет азагружать JavaScript каждый раз во время старта.

5.7 Настройка Netmanage Internet Chameleon WebSurfer

Netmanage WebSurfer поддерживает ручную настройку прокси и списки исключений для узлов или доменов, доступ к тороым не должен осущесвляться через прокси (эта информация верна для текущей версии WebSurfer 5.0). Выберите пункт Preferences из меню Settings. Щелкните на закладке Proxies. Выберите опции Use Proxy для HTTP, FTP и gopher. Для каждого из протоколов укажите также имя узла сервера Squid или IP-адрес, а также номер HTTP-порта для сервера Squid ( 3128 по умолчанию ) в поле Port. Для протоколов, которые ваш Squid не поддерживает, оставье поля пустыми.

См. это скриншот screen shot, если инструкция вас запутала.

В том же окне конфигурации вы можете найти кнопку выбора списка исключений, которая позволит вам указать те имена узлов или доменов, доступ к которым вы не хотите осущесвлять через прокси. Само по себе там все очевидно, но в любом случае гляньте на этот скриншот хотя бы для прикола.

5.8 Настройка прокси в Opera 2.12

Выберите Proxy Servers... из меню Preferences. Укажите каждый из протоклово, поддерживаемых вашим сервером Squid (по умолчанию HTTP, FTP и Gopher), а также адрес сервера Squid в виде имя_хоста:порт (типа mycache.example.com:3128 или 123.45.67.89:3128). Нажмите Okay для подтверждения установок.

Замечание:

-- Hume Smith

5.9 Как мне указать Squid использовать определенное имя пользователя для FTP?

Вставьте ваше имя пользователя в URL, к примеру:

        ftp://joecool@ftp.foo.org/
Squid должен запросить у вас пароль для вашей учетной записи. Вы также можете указать и имя и пароль в URL:
        ftp://joecool:secret@ftp.foo.org/
Однако, мы категорически не рекомендуем поступать подобным образом, т.к. любой может запросто подсмотреть ваш пароль.

5.10 Настройка броузеров для WPAD

by Mark Reynolds

You may like to start by reading the Internet-Draft that describes WPAD.

After reading the 8 steps below, if you don't understand any of the terms or methods mentioned, you probably shouldn't be doing this. Implementing wpad requires you to fully understand:

  1. web server installations and modifications.
  2. squid proxy server (or others) installation etc.
  3. Domain Name System maintenance etc.
Пожалуйста, не забрасывайте списко рассылки squid вопросами по настройке web-серверов или dns. See your system administrator, or do some more research on those topics.

This is not a recommendation for any product or version. As far as I know IE5 is the only browser out now implementing wpad. I think wpad is an excellent feature that will return several hours of life per month. Hopefully, all browser clients will implement it as well. But it will take years for all the older browsers to fade away though.

I have only focused on the domain name method, to the exclusion of the DHCP method. I think the dns method might be easier for most people. I don't currently, and may never, fully understand wpad and IE5, but this method worked for me. It may work for you.

But if you'd rather just have a go ...

  1. Create a standard netscape auto proxy config file. The sample provided there is more than adequate to get you going. No doubt all the other load balancing and backup scripts will be fine also.
  2. Store the resultant file in the document root directory of a handy web server as wpad.dat (Not proxy.pac as you may have previously done.)

    Andrei Ivanov notes that you should be able to use an HTTP redirect if you want to store the wpad.dat file somewhere else. You can probably even redirect wpad.dat to proxy.pac:

    Redirect /wpad.dat http://racoon.riga.lv/proxy.pac
    

  3. If you do nothing more, a url like http://www.your.domain.name/wpad.dat should bring up the script text in your browser window.
  4. Insert the following entry into your web server mime.types file. Maybe in addition to your pac file type, if you've done this before.
            application/x-ns-proxy-autoconfig       dat
    
    And then restart your web server, for new mime type to work.
  5. Assuming Internet Explorer 5, under Tools, Internet Options, Connections, Settings or Lan Settings, set ONLY Use Automatic Configuration Script to be the URL for where your new wpad.dat file can be found. i.e. http://www.your.domain.name/wpad.dat Test that that all works as per your script and network. There's no point continuing until this works ...
  6. Create/install/implement a DNS record so that wpad.your.domain.name resolves to the host above where you have a functioning auto config script running. You should now be able to use http://wpad.your.domain.name/wpad.dat as the Auto Config Script location in step 5 above.
  7. And finally, go back to the setup screen detailed in 5 above, and choose nothing but the Automatically Detect Settings option, turning everything else off. Best to restart IE5, as you normally do with any Microsoft product... And it should all work. Did for me anyway.
  8. One final question might be 'Which domain name does the client (IE5) use for the wpad... lookup?' It uses the hostname from the control panel setting. It starts the search by adding the hostname "WPAD" to current fully-qualified domain name. For instance, a client in a.b.Microsoft.com would search for a WPAD server at wpad.a.b.microsoft.com. If it could not locate one, it would remove the bottom-most domain and try again; for instance, it would try wpad.b.microsoft.com next. IE 5 would stop searching when it found a WPAD server or reached the third-level domain, wpad.microsoft.com.

Anybody using these steps to install and test, please feel free to make notes, corrections or additions for improvements, and post back to the squid list...

There are probably many more tricks and tips which hopefully will be detailed here in the future. Things like wpad.dat files being served from the proxy server themselves, maybe with a round robin dns setup for the WPAD host.

5.11 Настройка броузеров для WPAD с DHCP.

Вы также можете использовать DHCP при настройке броузеров для WPAD. Эта техника позволяет вам указать любой URL как PAC URL. Для ISC DHCPD добавьте такие строки в в ваш файл dhcpd.conf:

        option wpad code 252 = text;
        option wpad "http://www.example.com/proxy.pac"

Замените имя хоста на имя или адрес вашего собственного сервера.

5.12 IE 5.0x crops trailing slashes from FTP URL's

by Reuben Farrelly

There was a bug in the 5.0x releases of Internet Explorer in which IE cropped any trailing slash off an FTP URL. The URL showed up correctly in the browser's ``Address:'' field, however squid logs show that the trailing slash was being taken off.

An example of where this impacted squid if you had a setup where squid would go direct for FTP directory listings but forward a request to a parent for FTP file transfers. This was useful if your upstream proxy was an older version of Squid or another vendors software which displayed directory listings with broken icons and you wanted your own local version of squid to generate proper FTP directory listings instead. The workaround for this is to add a double slash to any directory listing in which the slash was important, or else upgrade to IE 5.5. (Or use Netscape)

5.13 IE 6.0 SP1 не работает при использовании аутентификации basic.

Когда вы используете basic-аутентификацию в Internet Explorer 6 SP1, вы можете столкнуться с проблемой при первом запуске Internet Explorer. Проблема проявляет себя в момент первой аутентификации, вы можете получить сообщение о ошибке "Page Cannot Be Displayed". Однако, если затем нажать на "Обновить", страница отображается корректно.

Это происходит только в момент после вашей аутентификации.

Это не ошибка в работе Squid. Microsoft повредила работу Basic Authentication в выпущенном IE6 SP1.

There is a knowledgebase article (KB 331906), касающаяся этой проблемы. The fix is to call Microsoft, open an incident referencing this KB article and they will send you a "hot fix". They do warn that this code is not "regression tested", но пока не было каких-либо сообщений, указывающих на то, что данное исправление повреждает что-либо еще. Файл, вызывающий проблему - wininet.dll.

Благодаря Joao Coutinho есть простое решение, исправляющее проблему:


Вперед Назад Содержание