отладка cgi скриптов apache

Выделенный сервер своими руками

Навигация

Облако тегов

Мои контакты

mail:
admin@dedicatesupport.com

Партнеры

Друзья

Счетчики

Настройка выполнения CGI скриптов в apache 2.0

Вторым вариантом настройки выполнения скриптов является использование директив AddHandler и SetHandler.
Пример:

Все файлы из папки /var/www/mydir при обращении в браузере http://www.ваш_домен.com/mydir/ будут исполняться как cgi скрипты.
Еще один вариант. В каталоге много html файлов. И там же нужно разрешить выполнение cgi скриптов. Тут нам поможет директива AddHandler. Пример:

Вот и все. Помещаем файл в соотвествующую директорию веб сервера и вызываем его браузером. При успешной настройке в окне браузера выведется строка Hello, World.На этом закончу маленькую заметку по настройке выполнения cgi скриптов для веб сервера apache.

Добрый день. Подскажите, как

Подскажите, как запустить JavaScript с помощью CGI-скрипта?

Требуется чистый запуск, без выдергивания значений или обработки данных.

Буду безмерно благодарен.

Подскажите, в каком файле

Подскажите, в каком файле нужно прописать эти директивы? Я поставил апач 2.2 и у меня файл httpd.conf пустой, пытался просто записать в него, но сервер не захотел запускаться Потом попытался записать в apache2.conf не могу найти подходящую строчку, и собственно после дополнения его сервер опять же не стартует.

Никак не могу понять, как

Никак не могу понять, как заставить Apache при обращении на, скажем, http://localhost выполнять http://localhost/cgi-bin/index.cgi?

Размести в корне сервера файл

Размести в корне сервера файл index.html следующего содержания:

Тупой редирект

делай так: 240-ая строка

делай так:
240-ая строка httpd.conf (в если там ничего не менял):
DirectoryIndex \cgi-bin\script.cgi
и будет тебе счастье =)

Самый верный и оптимальный

Самый верный и оптимальный вариант из всех предложенных

Источник

Apache Tutorial: Dynamic Content with CGI

See also

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

Introduction

The CGI (Common Gateway Interface) defines a way for a web server to interact with external content-generating programs, which are often referred to as CGI programs or CGI scripts. It is a simple way to put dynamic content on your web site, using whatever programming language you’re most familiar with. This document will be an introduction to setting up CGI on your Apache web server, and getting started writing CGI programs.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

Configuring Apache to permit CGI

In order to get your CGI programs to work properly, you’ll need to have Apache configured to permit CGI execution. There are several ways to do this.

ScriptAlias

The ScriptAlias directive tells Apache that a particular directory is set aside for CGI programs. Apache will assume that every file in this directory is a CGI program, and will attempt to execute it, when that particular resource is requested by a client.

The ScriptAlias directive looks like:

For example, if the URL http://www.example.com/cgi-bin/test.pl is requested, Apache will attempt to execute the file /usr/local/apache2/cgi-bin/test.pl and return the output. Of course, the file will have to exist, and be executable, and return output in a particular way, or Apache will return an error message.

CGI outside of ScriptAlias directories

CGI programs are often restricted to ScriptAlias ‘ed directories for security reasons. In this way, administrators can tightly control who is allowed to use CGI programs. However, if the proper security precautions are taken, there is no reason why CGI programs cannot be run from arbitrary directories. For example, you may wish to let users have web content in their home directories with the UserDir directive. If they want to have their own CGI programs, but don’t have access to the main cgi-bin directory, they will need to be able to run CGI programs elsewhere.

There are two steps to allowing CGI execution in an arbitrary directory. First, the cgi-script handler must be activated using the AddHandler or SetHandler directive. Second, ExecCGI must be specified in the Options directive.

Explicitly using Options to permit CGI execution

You could explicitly use the Options directive, inside your main server configuration file, to specify that CGI execution was permitted in a particular directory:

The above directive tells Apache to permit the execution of CGI files. You will also need to tell the server what files are CGI files. The following AddHandler directive tells the server to treat all files with the cgi or pl extension as CGI programs:

.htaccess files

User Directories

If you wish designate a cgi-bin subdirectory of a user’s directory where everything will be treated as a CGI program, you can use the following.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

Writing a CGI program

There are two main differences between «regular» programming, and CGI programming.

First, all output from your CGI program must be preceded by a MIME-type header. This is HTTP header that tells the client what sort of content it is receiving. Most of the time, this will look like:

Secondly, your output needs to be in HTML, or some other format that a browser will be able to display. Most of the time, this will be HTML, but occasionally you might write a CGI program that outputs a gif image, or other non-HTML content.

Apart from those two things, writing a CGI program will look a lot like any other program that you might write.

Your first CGI program

If you open your favorite browser and tell it to get the address

or wherever you put your file, you will see the one line Hello, World. appear in your browser window. It’s not very exciting, but once you get that working, you’ll have a good chance of getting just about anything working.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

But it’s still not working!

There are four basic things that you may see in your browser when you try to access your CGI program from the web:

The output of your CGI program Great! That means everything worked fine. If the output is correct, but the browser is not processing it correctly, make sure you have the correct Content-Type set in your CGI program. The source code of your CGI program or a «POST Method Not Allowed» message That means that you have not properly configured Apache to process your CGI program. Reread the section on configuring Apache and try to find what you missed. A message starting with «Forbidden» That means that there is a permissions problem. Check the Apache error log and the section below on file permissions. A message saying «Internal Server Error» If you check the Apache error log, you will probably find that it says «Premature end of script headers», possibly along with an error message generated by your CGI program. In this case, you will want to check each of the below sections to see what might be preventing your CGI program from emitting the proper HTTP headers.

File permissions

Also, if your program reads from, or writes to, any other files, those files will need to have the correct permissions to permit this.

Path information and environment

A common manifestation of this is the path to the script interpreter (often perl ) indicated in the first line of your CGI program, which will look something like:

Make sure that this is in fact the path to the interpreter.

Missing environment variables

If your CGI program depends on non-standard environment variables, you will need to assure that those variables are passed by Apache.

When you miss HTTP headers from the environment, make sure they are formatted according to RFC 2616, section 4.2: Header names must start with a letter, followed only by letters, numbers or hyphen. Any header violating this rule will be dropped silently.

Program errors

Most of the time when a CGI program fails, it’s because of a problem with the program itself. This is particularly true once you get the hang of this CGI stuff, and no longer make the above two mistakes. The first thing to do is to make sure that your program runs from the command line before testing it via the web server. For example, try:

cd /usr/local/apache2/cgi-bin
./first.pl

(Do not call the perl interpreter. The shell and Apache should find the interpreter using the path information on the first line of the script.)

Error logs

The error logs are your friend. Anything that goes wrong generates message in the error log. You should always look there first. If the place where you are hosting your web site does not permit you access to the error log, you should probably host your site somewhere else. Learn to read the error logs, and you’ll find that almost all of your problems are quickly identified, and quickly solved.

Suexec

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

What’s going on behind the scenes?

As you become more advanced in CGI programming, it will become useful to understand more about what’s happening behind the scenes. Specifically, how the browser and server communicate with one another. Because although it’s all very well to write a program that prints «Hello, World.», it’s not particularly useful.

Environment variables

Environment variables are values that float around you as you use your computer. They are useful things like your path (where the computer searches for the actual file implementing a command when you type it), your username, your terminal type, and so on. For a full list of your normal, every day environment variables, type env at a command prompt.

During the CGI transaction, the server and the browser also set environment variables, so that they can communicate with one another. These are things like the browser type (Netscape, IE, Lynx), the server type (Apache, IIS, WebSite), the name of the CGI program that is being run, and so on.

These variables are available to the CGI programmer, and are half of the story of the client-server communication. The complete list of required variables is at Common Gateway Interface RFC.

This simple Perl CGI program will display all of the environment variables that are being passed around. Two similar programs are included in the cgi-bin directory of the Apache distribution. Note that some variables are required, while others are optional, so you may see some variables listed that were not in the official list. In addition, Apache provides many different ways for you to add your own environment variables to the basic ones provided by default.

STDIN and STDOUT

Other communication between the server and the client happens over standard input ( STDIN ) and standard output ( STDOUT ). In normal everyday context, STDIN means the keyboard, or a file that a program is given to act on, and STDOUT usually means the console or screen.

The «special format» is very simple. A field name and its value are joined together with an equals (=) sign, and pairs of values are joined together with an ampersand (&). Inconvenient characters like spaces, ampersands, and equals signs, are converted into their hex equivalent so that they don’t gum up the works. The whole data string might look something like:

Your program is then responsible for splitting that string up into useful information. Fortunately, there are libraries and modules available to help you process this data, as well as handle other of the aspects of your CGI program.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

CGI modules/libraries

When you write CGI programs, you should consider using a code library, or module, to do most of the grunt work for you. This leads to fewer errors, and faster development.

If you’re writing CGI programs in C, there are a variety of options. One of these is the CGIC library, from https://web.mit.edu/wwwdev/www/cgic.html.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

For more information

The current CGI specification is available in the Common Gateway Interface RFC.

When you post a question about a CGI problem that you’re having, whether to a mailing list, or to a newsgroup, make sure you provide enough information about what happened, what you expected to happen, and how what actually happened was different, what server you’re running, what language your CGI program was in, and, if possible, the offending code. This will make finding your problem much simpler.

Note that questions about CGI problems should never be posted to the Apache bug database unless you are sure you have found a problem in the Apache source code.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

Comments

Copyright 2021 The Apache Software Foundation.
Licensed under the Apache License, Version 2.0.

Источник

Apache, fastcgi и c++: «Hello, world»

Вступление: FastCGI

О том что такое fastcgi можно прочитать здесь. Если говорить коротко, то это CGI-программа обрабатывающая запросы в цикле. Её преимущество над обычной CGI-программой заключается в что она запускается один раз для обработки множества запросов.

Веб-сервер

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

Возможные альтернативы:
Nginx и Lighttpd имеют «родную» поддержку интерфейса fastcgi и их использование более предпочтительно на «продакшн»-серверах. Можно также использовать MS IIS.

Mod_fastcgi, mod_fcgid

Мне известно два модуля при помощи которых осуществляется поддержка fastcgi-интерфейса в апаче, это mod_fastcgi и mod_fcgid.
Mod_fastcgi разрабатывается компанией Open Market c 1997года. Последняя версия 2.4.6 была обновлена 13го ноября 2007 и, как уверяют авторы, является очень стабильной.
Mod_fcgi, судя по домену, разрабатывается китайскими программистами. Последняя версия 2.2 датирована 31июля 2007. Отличительными особенностями от mod_fastcgi являются: новая модель управления fastcgi-программами, обнаружение ошибок в работе fastcgi-программ. Модуль имеет бинарную совместимость и поэтому перекомпилировать программы, работающие под mod_fastсgi нет необходимости.
Используя development kit с fastcgi.com для разработки программ, я решил, что более уместно будет использовать mod_fastcgi, т.к. они используют общую библиотеку libfcgi.

Типы запуска fastcgi-программ

Используя mod_fastcgi можно запускать программы тремя различными способами: динамически, статически и удаленно.

Методы взаимодействия:

Меня интересует прежде всего работа с tcp socket’ом и удаленным способом запуска fastcgi-программы, потому что это дает совместимость работы с другими веб-серверами, а также предоставляет более простую возможность отладки.

Fastcgi libraries

Не так уж и много существует библиотек помогающих создавать fastcgi-программы на C/C++. Наиболее популярна libfcgi.lib, которая поставляется в составе development kit от fastcgi.com. Библиотека, честно сказать, предоставляет небогатый функционал для работы.
Существует также Fastcgi++ библиотека классов на С++.
Так как это моя первая fastcgi-программа, то я буду использовать старую, проверенную библиотеку libfcgi.lib.

Hello_world.fcgi

Программа использует для коммуникации TCP Socket, открывая порт номер 9000. В браузере выводится строка «Fastcgi: Hello, world».
Используемые функции:
int FCGX_Init( void );
— Инициализация библиотеки FCGX
int FCGX_OpenSocket( const char *path, int backlog);
— Открывает слушающий сокет (Параметры: path – имя сокета, backlog – глубина стека запросов ).
int FCGX_InitRequest(FCGX_Request *request, int sock, int flags);
— Инициализируем структуру запроса для использования внутри FCGX_ Accept_r (Параметры: request – указатель на структуру запроса, sock – слушающий сокет используемый совместно с request, flags – флаг запроса (доступные флаги: FCGI_FAIL_ACCEPT_ON_INTR – не вызывать повторно accept при разрыве ).
int FCGX_Accept_r(FCGX_Request *request);
— Получает новый запрос на обработку.

Полный текст программы:
#include

int main( int argc, char * const argv[] )

std::string port= «:9000» ; //Задаем номер порта TCP

int listenQueueBacklog = 400; //Глубина стека запросов

FCGX_Stream *in, *out, *err;

if (FCGX_Init()) exit(1); //Инициализируем библиотеку перед работой.

int listen_socket = FCGX_OpenSocket(port.c_str(), listenQueueBacklog); //Открываем новый слушающий сокет

if (listen_socket if (FCGX_InitRequest(&request, listen_socket, 0)) exit(1); //Инициализируем структуру запроса

while (FCGX_Accept_r(&request) == 0)

FCGX_FPrintF(request.out, «Content-type: text/html\r\n\r\n fastcgi \n

Fastcgi: Hello world.

FCGX_Finish_r(&request); //Завершаем запрос

Vhosts.conf

NameVirtualHost 127.0.0.1: 80
VirtualHost 127.0.0.1: 80 >
ServerAdmin mail@localhost
DocumentRoot «C:/Apache2/cgi-bin»
ServerName «helloworld.local»

Источник

Apache Module mod_cgi

Summary

Any file that has the handler cgi-script will be treated as a CGI script, and run by the server, with its output being returned to the client. Files acquire this handler either by having a name containing an extension defined by the AddHandler directive, or by being in a ScriptAlias directory.

For an introduction to using CGI scripts with Apache, see our tutorial on Dynamic Content With CGI.

When using a multi-threaded MPM under unix, the module mod_cgid should be used in place of this module. At the user level, the two modules are essentially identical.

отладка cgi скриптов apache. SupportApache small. отладка cgi скриптов apache фото. отладка cgi скриптов apache-SupportApache small. картинка отладка cgi скриптов apache. картинка SupportApache small. mail: admin@dedicatesupport.com

Topics

Directives

Bugfix checklist

See also

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

CGI Environment variables

The server will set the CGI environment variables as described in the CGI specification, with the following provisions:

This module also leverages the core functions ap_add_common_vars and ap_add_cgi_vars to add environment variables like:

DOCUMENT_ROOT Set with the content of the related DocumentRoot directive. SERVER_NAME The fully qualified domain name related to the request. SERVER_ADDR The IP address of the Virtual Host serving the request. SERVER_ADMIN Set with the content of the related ServerAdmin directive.

For an exhaustive list it is suggested to write a basic CGI script that dumps all the environment variables passed by Apache in a convenient format.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

CGI Debugging

Debugging CGI scripts has traditionally been difficult, mainly because it has not been possible to study the output (standard output and error) for scripts which are failing to run properly. These directives provide more detailed logging of errors when they occur.

CGI Logfile Format

When configured, the CGI error log logs any CGI which does not execute properly. Each CGI script which fails to operate causes several lines of information to be logged. The first two lines are always of the format:

%% [ time ] request-line
%% HTTP-status CGI-script-filename

If the error is that CGI script cannot be run, the log file will contain an extra two lines:

Alternatively, if the error is the result of the script returning incorrect header information (often due to a bug in the script), the following information is logged:

%request
All HTTP request headers received
POST or PUT entity (if any)
%response
All headers output by the CGI script
%stdout
CGI standard output
%stderr
CGI standard error

(The %stdout and %stderr parts may be missing if the script did not output anything on standard output or standard error).

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

ScriptLog Directive

Example

This log will be opened as the user the child processes run as, i.e. the user specified in the main User directive. This means that either the directory the script log is in needs to be writable by that user or the file needs to be manually created and set to be writable by that user. If you place the script log in your main logs directory, do NOT change the directory permissions to make it writable by the user the child processes run as.

Note that script logging is meant to be a debugging feature when writing CGI scripts, and is not meant to be activated continuously on running servers. It is not optimized for speed or efficiency, and may have security problems if used in a manner other than that for which it was designed.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

ScriptLogBuffer Directive

The size of any PUT or POST entity body that is logged to the file is limited, to prevent the log file growing too big too quickly if large bodies are being received. By default, up to 1024 bytes are logged, but this can be changed with this directive.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

ScriptLogLength Directive

ScriptLogLength can be used to limit the size of the CGI script logfile. Since the logfile logs a lot of information per CGI error (all request headers, all script output) it can grow to be a big file. To prevent problems due to unbounded growth, this directive can be used to set an maximum file-size for the CGI logfile. If the file exceeds this size, no more information will be written to it.

отладка cgi скриптов apache. up. отладка cgi скриптов apache фото. отладка cgi скриптов apache-up. картинка отладка cgi скриптов apache. картинка up. mail: admin@dedicatesupport.com

Comments

Copyright 2021 The Apache Software Foundation.
Licensed under the Apache License, Version 2.0.

Источник

CGI Apache настройка отдачи cgi скриптов

Потребуется написать простейший CGI скрипт — сделаем это на bash, также нужно активировать соответствующий модуль Apache.

Прежде всего приводим конфигурационный файл дефолтного виртуального хоста apache2 в соответствие приведенному ниже образцу

ServerName www.example.com

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Опционально — в /etc/hosts добавляем строку, согласно которой при обращении к www.example.com будет задействоваться вирт. хост на локальной машине

127.0.01 www.example.com

Включаем модуль веб-сервера и перезапускаем сервер

Создаем каталог, в котором будут размещаться скрипты и переходим в него

Далее нужно написать какой-то скрипт. Пусть он выводит слово hello и актуальное время обращения к скрипту

#!/bin/bash
echo Content-type: text/plain
echo «»

echo «hello»

Как любой bash скрипт он должен быть исполняемым

Настройка CGI Apache на этом завершена — теперь в браузере достаточно обратиться по адресу localhost/cgi-bin/script.cgi чтобы увидеть результат.

Поскольку ранее в /etc/hosts добавили нужное правило тот же вывод можно получить обратившись к www.example.com/cgi-bin/script.cgi

CGI скрипты требуют прав на исполнение и небезопасны, если скрипт написан плохо ему можно передать любые параметры и получить доступ к хост системе сервера. CGI в настоящее время используется ограниченно, в основном для административных скриптов, для сайтов применяется более безопасный способ исполнения — fastcgi

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *