Форум программистов, компьютерный форум, киберфорум
Apache, htaccess
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.58/88: Рейтинг темы: голосов - 88, средняя оценка - 4.58
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22

Как убрать расширение .php на страницах своего сайта? Apache 2.2.22

09.07.2013, 22:34. Показов 18073. Ответов 49
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Доброго времени суток!
Начал изучать php и задался интересным вопросом, как убрать расширение .php на страницах своего сайта,
расположенного на локальном сервере (сервер Apache 2.2.22).
Гугл не помог решить вопрос, любые действия заканчиваются тем, что расширение убрать нельзя,
иначе 404-ый статус. Помогите, пожалуйста, разобраться с этим вопросом.

Предпринимал следующие попытки убрать расширение:

Кликните здесь для просмотра всего текста
Терминал:
Bash
1
sudo a2enmod rewrite
Теперь он отвечает: Module rewrite already enabled
Bash
1
sudo nano /etc/apache2/sites-available/default
Изменил данные, получив:
Code
1
2
3
4
5
6
<Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
    </Directory>
Bash
1
sudo nano /etc/apache2/sites-available/default-ssl
Тоже изменил строку AllowOverride None на AllowOverride all:
Code
1
2
3
4
5
6
<Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
    </Directory>
В файл .htaccess внёс следующее:
Code
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
И за всё это время я очень много раз перезагружал сервер:
Bash
1
sudo apache2ctl restart
И:
Bash
1
sudo /etc/init.d/apache2 restart
Файл .htaccess, собственно, лежит в директиве сайта, который делаю, т.е. "/var/www/poetica".
Сервер apache 2.2.22, система linux ubuntu 13.04.
Страницы открываются как и раньше, т.е. следующие страницы спокойно работают:
http://127.0.0.1/poetica/ (http://127.0.0.1/poetica/index.php)
http://127.0.0.1/poetica/registration.php
Если убрать .php в индексе или в регистрации, выдаётся 404-ый статус:
Not Found
The requested URL /poetica/index was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80

Может кто-то сталкивался с подобной проблемой ранее и сможет подсказать как её решить?
Заранее благодарен! Всем доброго времени суток и удачного программирования!)
Надеюсь, статья сможет помочь не только мне, но и "облегчит жизнь" другим новичкам в php.

Добавлено через 2 часа 17 минут
Быть может, допущена какая-то ошибка? Забыл уточнить, файл /etc/apache2/apache2.conf также менял, изменения:
строка:
Code
1
2
3
4
5
6
AccessFileName .htaccess
>>> строки:
AccessFileName .htaccess
    <Directory "/www/poetica">
        AllowOverride All
    </Directory>
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
09.07.2013, 22:34
Ответы с готовыми решениями:

Как убрать Название сайта на всех страницах
Такая ситуация что название страницы генерируется на всех страницах так же на главной. Вот только они все слепленные получаются как убрать...

Как убрать вывод компонента на некоторых страницах сайта
Добрый день. В процессе создания сайта на joomla возник следующий вопрос: как убрать вывод компонента не на главной странице, а на...

Отображение меню на страницах сайта кодом <?php include $_SERVER['DOCUMENT_ROOT'].'/menu.php'; ?>
Перенёс сайт с одного хостинга на другой. Перестал работать код &lt;?php include $_SERVER.'/menu.php'; ?&gt; Голову уже сломал, не пойму...

49
123 / 123 / 82
Регистрация: 03.01.2013
Сообщений: 242
09.07.2013, 23:55
а вы где-то такое видели? Можна попробывать просто по названиях каталогов, типа images/index.php или template/index.php если заходить на http://127.9.9.1/images то какраз расш. файла (.php) не будет, будет отображатся информация с index.php в images
1
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 00:04  [ТС]
ntrx, Доброй ночи!
Если я правильно понял, предлагается каждый отдельный файл с расширением .php (например, registration.php) запихать в одноимённую этому файлу папку и сделать индексом?
Интересный вариант, спасибо! Но тогда, если я не ошибаюсь, получится что и в папке "/images" придётся делать для каждого файла по папочке?
А как тогда инклюдить? "include '/images/index.php'; include '/images/1/index.php';" ?
"а вы где-то такое видели?" - Да, судя по форумам, гуглу и хабру - это делают постоянно (применяют rewrite), но, видно что-то у меня пошло не так...
0
123 / 123 / 82
Регистрация: 03.01.2013
Сообщений: 242
10.07.2013, 00:07
На хабре такого не видел, может Вы покажете?
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 00:22  [ТС]
Цитата Сообщение от ntrx Посмотреть сообщение
На хабре такого не видел, может Вы покажете?
--

В следующем примере убирают личшнее слово "glavnaya" с помощью rewrite:
http://habrahabr.ru/qa/12082/

В следующем примере цитирую:
"Итак, что нужно. Чтобы ссылка example.com/forum/blog/0/lalala была сокращена до example.com/blog/lalala
Т.е человек набирает в браузере example.com/blog/lalala и у него эта ссылка открывается без изменения пути в бразуере но обрабатывается по пути example.com/forum/blog/0/lalala" . Всё это с помощью rewrite:
http://habrahabr.ru/qa/27461/

Следующий пример также интересен, тут убирают из ссылок символы "&", "?" и д.р. с помощью rewrite:
http://habrahabr.ru/post/24666/
0
123 / 123 / 82
Регистрация: 03.01.2013
Сообщений: 242
10.07.2013, 00:49
http://habrahabr.ru/qa/12082/ достаточно почитать коментов..
1
0 / 0 / 0
Регистрация: 07.07.2013
Сообщений: 11
10.07.2013, 01:34
Не силён в этом но вроде работает.


Code
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/images/|/css/|/javascript/)$
RewriteRule ^([a-zA-Z0-9]+)/$  /$1.php [QSA,L]
RewriteRule ^([a-zA-Z0-9]+)$  /$1.php [QSA,L]
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 13:26  [ТС]
Цитата Сообщение от soleg Посмотреть сообщение
Не силён в этом но вроде работает.


Code
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/images/|/css/|/javascript/)$
RewriteRule ^([a-zA-Z0-9]+)/$  /$1.php [QSA,L]
RewriteRule ^([a-zA-Z0-9]+)$  /$1.php [QSA,L]
--
Не помогло
Not Found
The requested URL /poetica/registration was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80
====
Кстати, если прописать билеберду в .htaccess , например "fdsgshshtrhm", после rewrite on то выдаёт уже не 400 ошибку как сейчас, а 500, что говорит о том, что сам реврайт включен и работает, но почему-то не хочет заменять .php

Добавлено через 4 минуты
ntrx, не работает ничего оттуда
0
0 / 0 / 0
Регистрация: 07.07.2013
Сообщений: 11
10.07.2013, 14:21
Цитата Сообщение от Сергей Прокошин Посмотреть сообщение
--
Не помогло
Not Found
The requested URL /poetica/registration was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80
====
Я дал пример для такого вида ссылки
site.ru/registration

если же ты хочешь использовать такого вида ссылки
/poetica/registration

Т.е. стоит просто добавить в условие строки

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
RewriteEngine On
 
#указываем директории которые будут игнорироваться реврайтом.
RewriteCond %{REQUEST_URI} !^(/images/|/css/|/javascript/)$
 
# это для ссылок вида /poetica/registration .
# т.е. poetica - это директория
# а registration  это php-файл в директории  poetica
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$  /$1/$2.php [QSA,L]
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$  /$1/$2.php [QSA,L]
 
# А это для простых ссилок вида site.ru/registration
# где  registration это файл registration.php в корне сайта.
RewriteRule ^([a-zA-Z0-9]+)/$  /$1.php [QSA,L]
RewriteRule ^([a-zA-Z0-9]+)$  /$1.php [QSA,L]
Конечно же это можно оптимизировать, но универсального решения всё равно не получить, да и используя такие условия можно очень гибко настроить для сайта чпу.

Только стоит заметить, хотя это и так понятно, что теперь прописав в адресе site.ru/poetica/ он не откроет индексный файл в директории poetica, а будет искать файл $site.ru/poetica.php


Цитата Сообщение от Сергей Прокошин Посмотреть сообщение
Кстати, если прописать билеберду в .htaccess , например "fdsgshshtrhm", после rewrite on то выдаёт уже не 400 ошибку как сейчас, а 500, что говорит о том, что сам реврайт включен и работает, но почему-то не хочет заменять .php
500 ошибка в данном случае говорит о неверном синтексисе файла .htaccess

Добавлено через 8 минут
[QSA,L] - позволяет данному условию принимать GET параметры. Т.е. можно использовать такого вида линки
HTML5
1
site.ru/poetica/registration/?param1=value
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 14:41  [ТС]
soleg, Спасибо! Попробую!
Доброго дня!

Добавлено через 12 минут
Попробовал два варианта, оба не дали результата:
Code
1
2
3
4
5
6
7
8
9
10
11
12
RewriteEngine On
#указываем директории которые будут игнорироваться реврайтом.
RewriteCond %{REQUEST_URI} !^(/images/|/css/|/javascript/|/img/)$
# это для ссылок вида /poetica/registration .
# т.е. poetica - это директория
# а registration  это php-файл в директории  poetica
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$  /$1/$2.php [QSA,L]
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$  /$1/$2.php [QSA,L]
# А это для простых ссилок вида site.ru/registration
# где  registration это файл registration.php в корне сайта.
RewriteRule ^([a-zA-Z0-9]+)/$  /$1.php [QSA,L]
RewriteRule ^([a-zA-Z0-9]+)$  /$1.php [QSA,L]
и во втором удалил две последнии строки
--
Итог:
http://127.0.0.1/poetica/index.php открывается
http://127.0.0.1/poetica/ открывается (то же самое что и index.php)
http://127.0.0.1/poetica/registration.php открывается
Ни в одном варианте ни
http://127.0.0.1/poetica/index
ни http://127.0.0.1/poetica/registration
не открываются, 404 статус Not Found
The requested URL /poetica/index was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80
Not Found
The requested URL /poetica/registration was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80
0
0 / 0 / 0
Регистрация: 07.07.2013
Сообщений: 11
10.07.2013, 14:50
Странно у меня всё работает, я всегда использую такие выражения. Может дело в том что ты указываешь IP,а не домен.
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 15:07  [ТС]
Сервер на локалке, пока больше нечего указывать, собственно, я же ещё не размещал в глобальную сеть... В директории /var/www/ у меня лежат сразу 2 сайта в различных папках, в папке /var/www/poetica/ лежат исходники сайта который делаю - кучкой файлов php, файлом css, собственно, файлы php, которые я запускаю через инклюд, ну и папка /img в которой картинки для сайта. Может, .htaccess захватывает include функцию? Но вроде не в этом проблема - просто белый экран с ошибкой сценария php бы выдавало.
Индекс у меня - index.php
0
Почетный модератор
Эксперт HTML/CSSЭксперт PHP
 Аватар для KOPOJI
16844 / 6724 / 880
Регистрация: 12.06.2012
Сообщений: 19,967
10.07.2013, 15:19
точно везде прописано All вместо None в AllowOverride ?

Добавлено через 1 минуту

Не по теме:

Цитата Сообщение от Сергей Прокошин Посмотреть сообщение
Начал изучать php и задался интересным вопросом, как убрать расширение .php на страницах своего сайта
и правда, интересный вопрос. Особенно интересно, каким образом связано изучение php(яп) и убирание расширения php(сервер) :)

0
0 / 0 / 0
Регистрация: 07.07.2013
Сообщений: 11
10.07.2013, 15:22
невнимательно я прочитал похоже изначально.
Мой пример будет работать если сайт расположен в корневой директории, т.е. в твоём случае в /www/.

Попробуй в директории /www/ создать htaccess файл с

Code
1
2
3
4
5
6
7
8
9
10
RewriteEngine On
 
#указываем директории которые будут игнорироваться реврайтом.
RewriteCond %{REQUEST_URI} !^(/poetica/images/|/poetica/css/|/poetica/javascript/)$
 
# это для ссылок вида /poetica/registration .
# т.е. poetica - это директория
# а registration  это php-файл в директории  poetica
RewriteRule ^poetica/([a-zA-Z0-9]+)/$  /poetica/$1.php [QSA,L]
RewriteRule ^poetica/([a-zA-Z0-9]+)$  /poetica/$1.php [QSA,L]
все примеры проверяю перед тем как писать, поэтому у меня всё работает.
0
Почетный модератор
Эксперт HTML/CSSЭксперт PHP
 Аватар для KOPOJI
16844 / 6724 / 880
Регистрация: 12.06.2012
Сообщений: 19,967
10.07.2013, 15:25
Цитата Сообщение от Сергей Прокошин Посмотреть сообщение
Code
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
попробуйте так
Code
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L,QSA]
Добавлено через 20 секунд
soleg, RewriteBase ?
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 15:28  [ТС]
Цитата Сообщение от KOPOJI Посмотреть сообщение
точно везде прописано All вместо None в AllowOverride ?
Вот состав файлов:

/etc/apache2/apache2.conf
Кликните здесь для просмотра всего текста
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.2/ for detailed information about
# the directives and /usr/share/doc/apache2-common/README.Debian.gz about
# Debian specific hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.
 
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf.d
#   |   `-- *
#   `-- sites-enabled
#       `-- *
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
#   In order to avoid conflicts with backup files, the Include directive is
#   adapted to ignore files that:
#   - do not begin with a letter or number
#   - contain a character that is neither letter nor number nor _-.
#   - contain .dpkg
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections, and which
#   of these ports are used for name based virtual hosts.
#
# * Configuration files in the mods-enabled/ and sites-enabled/ directories
#   contain particular configuration snippets which manage modules or virtual
#   host configurations, respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite. See
#   their respective man pages for detailed information.
#
# * Configuration files in the conf.d directory are either provided by other
#   packages or may be added by the local administrator. Local additions
#   should start with local- or end with .local or .local.conf to avoid name
#   clashes. All files in conf.d are included 
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.
 
 
# Global configuration
#
 
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation (available
# at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"
 
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
LockFile ${APACHE_LOCK_DIR}/accept.lock
 
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
 
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
 
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
 
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
 
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
 
##
## Server-Pool Size Regulation (MPM specific)
## 
 
# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
 
# worker MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadLimit: ThreadsPerChild can be changed to this maximum value during a
#              graceful restart. ThreadLimit can only be changed by stopping
#              and starting Apache.
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
 
# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_event_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
 
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
 
#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess
    <Directory "/www/poetica">
        AllowOverride All
    </Directory>
 
#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>
 
#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
# It is also possible to omit any default MIME type and let the
# client's browser guess an appropriate action instead. Typically the
# browser will decide based on the file's extension then. In cases
# where no good assumption can be made, letting the default MIME type
# unset is suggested  instead of forcing the browser to accept
# incorrect  metadata.
#
DefaultType None
 
 
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
 
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
 
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
 
# Include module configuration:
Include mods-enabled/*.load
Include mods-enabled/*.conf
 
# Include list of ports to listen on and which to use for name based vhosts
Include ports.conf
 
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
 
# Include of directories ignores editors' and dpkg's backup files,
# see the comments above for details.
 
# Include generic snippets of statements
Include conf.d/
 
# Include the virtual host configurations:
Include sites-enabled/
 
ServerName poetica

/etc/apache2/sites-available/default
Кликните здесь для просмотра всего текста
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
 
    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
 
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>
 
    ErrorLog ${APACHE_LOG_DIR}/error.log
 
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
 
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

/etc/apache2/sites-available/default-ssl
Кликните здесь для просмотра всего текста
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
    ServerAdmin webmaster@localhost
 
    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
    </Directory>
 
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>
 
    ErrorLog ${APACHE_LOG_DIR}/error.log
 
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
 
    CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
 
    #   SSL Engine Switch:
    #   Enable/Disable SSL for this virtual host.
    SSLEngine on
 
    #   A self-signed (snakeoil) certificate can be created by installing
    #   the ssl-cert package. See
    #   /usr/share/doc/apache2.2-common/README.Debian.gz for more info.
    #   If both key and certificate are stored in the same file, only the
    #   SSLCertificateFile directive is needed.
    SSLCertificateFile    /etc/ssl/certs/ssl-cert-snakeoil.pem
    SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
 
    #   Server Certificate Chain:
    #   Point SSLCertificateChainFile at a file containing the
    #   concatenation of PEM encoded CA certificates which form the
    #   certificate chain for the server certificate. Alternatively
    #   the referenced file can be the same as SSLCertificateFile
    #   when the CA certificates are directly appended to the server
    #   certificate for convinience.
    #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt
 
    #   Certificate Authority (CA):
    #   Set the CA certificate verification path where to find CA
    #   certificates for client authentication or alternatively one
    #   huge file containing all of them (file must be PEM encoded)
    #   Note: Inside SSLCACertificatePath you need hash symlinks
    #         to point to the certificate files. Use the provided
    #         Makefile to update the hash symlinks after changes.
    #SSLCACertificatePath /etc/ssl/certs/
    #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt
 
    #   Certificate Revocation Lists (CRL):
    #   Set the CA revocation path where to find CA CRLs for client
    #   authentication or alternatively one huge file containing all
    #   of them (file must be PEM encoded)
    #   Note: Inside SSLCARevocationPath you need hash symlinks
    #         to point to the certificate files. Use the provided
    #         Makefile to update the hash symlinks after changes.
    #SSLCARevocationPath /etc/apache2/ssl.crl/
    #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl
 
    #   Client Authentication (Type):
    #   Client certificate verification type and depth.  Types are
    #   none, optional, require and optional_no_ca.  Depth is a
    #   number which specifies how deeply to verify the certificate
    #   issuer chain before deciding the certificate is not valid.
    #SSLVerifyClient require
    #SSLVerifyDepth  10
 
    #   Access Control:
    #   With SSLRequire you can do per-directory access control based
    #   on arbitrary complex boolean expressions containing server
    #   variable checks and other lookup directives.  The syntax is a
    #   mixture between C and Perl.  See the mod_ssl documentation
    #   for more details.
    #<Location />
    #SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
    #            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
    #            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
    #            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
    #            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
    #           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
    #</Location>
 
    #   SSL Engine Options:
    #   Set various options for the SSL engine.
    #   o FakeBasicAuth:
    #     Translate the client X.509 into a Basic Authorisation.  This means that
    #     the standard Auth/DBMAuth methods can be used for access control.  The
    #     user name is the `one line' version of the client's X.509 certificate.
    #     Note that no password is obtained from the user. Every entry in the user
    #     file needs this password: `xxj31ZMTZzkVA'.
    #   o ExportCertData:
    #     This exports two additional environment variables: SSL_CLIENT_CERT and
    #     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
    #     server (always existing) and the client (only existing when client
    #     authentication is used). This can be used to import the certificates
    #     into CGI scripts.
    #   o StdEnvVars:
    #     This exports the standard SSL/TLS related `SSL_*' environment variables.
    #     Per default this exportation is switched off for performance reasons,
    #     because the extraction step is an expensive operation and is usually
    #     useless for serving static content. So one usually enables the
    #     exportation for CGI and SSI requests only.
    #   o StrictRequire:
    #     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
    #     under a "Satisfy any" situation, i.e. when it applies access is denied
    #     and no other module can change it.
    #   o OptRenegotiate:
    #     This enables optimized SSL connection renegotiation handling when SSL
    #     directives are used in per-directory context.
    #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
        SSLOptions +StdEnvVars
    </Directory>
 
    #   SSL Protocol Adjustments:
    #   The safe and default but still SSL/TLS standard compliant shutdown
    #   approach is that mod_ssl sends the close notify alert but doesn't wait for
    #   the close notify alert from client. When you need a different shutdown
    #   approach you can use one of the following variables:
    #   o ssl-unclean-shutdown:
    #     This forces an unclean shutdown when the connection is closed, i.e. no
    #     SSL close notify alert is send or allowed to received.  This violates
    #     the SSL/TLS standard but is needed for some brain-dead browsers. Use
    #     this when you receive I/O errors because of the standard approach where
    #     mod_ssl sends the close notify alert.
    #   o ssl-accurate-shutdown:
    #     This forces an accurate shutdown when the connection is closed, i.e. a
    #     SSL close notify alert is send and mod_ssl waits for the close notify
    #     alert of the client. This is 100% SSL/TLS standard compliant, but in
    #     practice often causes hanging connections with brain-dead browsers. Use
    #     this only for browsers where you know that their SSL implementation
    #     works correctly.
    #   Notice: Most problems of broken clients are also related to the HTTP
    #   keep-alive facility, so you usually additionally want to disable
    #   keep-alive for those clients, too. Use variable "nokeepalive" for this.
    #   Similarly, one has to force some clients to use HTTP/1.0 to workaround
    #   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
    #   "force-response-1.0" for this.
    BrowserMatch "MSIE [2-6]" \
        nokeepalive ssl-unclean-shutdown \
        downgrade-1.0 force-response-1.0
    # MSIE 7 and newer should be able to use keepalive
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
 
</VirtualHost>
</IfModule>
0
Почетный модератор
Эксперт HTML/CSSЭксперт PHP
 Аватар для KOPOJI
16844 / 6724 / 880
Регистрация: 12.06.2012
Сообщений: 19,967
10.07.2013, 15:29
Цитата Сообщение от Сергей Прокошин Посмотреть сообщение
/etc/apache2/sites-available/default
здесь надо было менять, а не в основном конфиге. default-ssl можно не трогать вообще, насколько помню.
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 15:46  [ТС]
Цитата Сообщение от KOPOJI Посмотреть сообщение
попробуйте так
Code
1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L,QSA]
Добавлено через 20 секунд
soleg, RewriteBase ?
Not Found
The requested URL /poetica/registration was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80

Добавлено через 5 минут
Цитата Сообщение от KOPOJI Посмотреть сообщение
здесь надо было менять, а не в основном конфиге. default-ssl можно не трогать вообще, насколько помню.
Bash
1
sudo nano /etc/apache2/sites-available/default-ssl
Поставил:
Code
1
2
3
4
5
6
 <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
Bash
1
2
sudo /etc/init.d/apache2 restart
 * Restarting web server apache2                                                 ... waiting ....                                                        [ OK ]
... обновил страницу
Not Found
The requested URL /poetica/registration was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80

Добавлено через 5 минут
soleg, таже ошибка.. 404

Добавлено через 5 минут
KOPOJI, изменил обратно /etc/apache2/apache2.conf
Bash
1
2
3
4
sudo nano /etc/apache2/apache2.conf
[CODE]AccessFileName .htaccess #оставил в блоке аксесс и рестарт сервера[/CODE]
sudo /etc/init.d/apache2 restart
 * Restarting web server apache2                                                 ... waiting                                                             [ OK ]
--
Not Found
The requested URL /poetica/registration was not found on this server.
Apache/2.2.22 (Ubuntu) Server at 127.0.0.1 Port 80
0
Почетный модератор
Эксперт HTML/CSSЭксперт PHP
 Аватар для KOPOJI
16844 / 6724 / 880
Регистрация: 12.06.2012
Сообщений: 19,967
10.07.2013, 16:14
Сергей Прокошин, а причем тут default-ssl ?
0
 Аватар для Сергей Прокошин
0 / 0 / 0
Регистрация: 09.07.2013
Сообщений: 22
10.07.2013, 16:39  [ТС]
Цитата Сообщение от KOPOJI Посмотреть сообщение
Сергей Прокошин, а причем тут default-ssl ?
Ну вы же написали цитирую: "default-ssl можно не трогать вообще" , я и поменял на значение по умолчанию.
Изначально я подумал что и этот файл нужно менять. В любом случае сейчас мод включен, AllowOverride All в файле default стоит.
Файл apache2.conf тоже в прежнем состоянии.

Добавлено через 8 минут
Возможно проблема зарыта где-то глубже. Через TeamViewer программист тоже не смог помочь мне. Ладно.
Сейчас это не проблема самой первой необходимости. Нужно делать сайт
Закройте, наверно, пожалуйста, топик, но если у кого вдруг появится какое-то явное соображение на этот счёт,
буду рад видеть в личке
Правда сам ответить вроде пока не смогу
Всем спасибо за советы!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
10.07.2013, 16:39
Помогаю со студенческими работами здесь

Убрать расширение .php в .htaccess
Здравствуйте! Я понимаю, что данная тема давно заезженная. Но все же, актуальна для меня.. Нужно в .htaccess поменять ВСЕ php страницы,...

Убрать расширение php в адресной строке
Всем привет! Прочитал, что это можно сделать при помощи файла .htaccess. Создал файл в корневом каталоге сайта, т.е. там где лежат все...

Убрать точку и расширение php в переменной
Может запутанно написал тему, извините, вопрос: Есть к примеру код: $a=$_SERVER; echo $a; выдает к примерно такое:...

Отображение div-а на страницах сайта средствами php
Здравствуйте, такая проблема: Делаю вывод html кода средствами php на сайте вот так $url = $_SERVER; if ($url == '/video') { echo...

Не отправляются письма с сайта (PHP, Apache 2)
Есть проблема с отправкой писем с сайта, перепробовал первые 3 страниц выдачи яндекса и гугла, ничего не получается, с библиотекой jquery и...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11680&amp;d=1772460536 Одним из. . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru