Htaccess html не работает

.htaccess не работает apache

У меня есть сервер из сервиса AWS EC2, работающий в Linux Ubuntu, и я установил apache, php и mysql.

Я добавил .htaccess файл в корне моего документа /var/www/html ,

Я ввел этот код в нем:
ErrorDocument 404 /var/www/html/404.php и это все еще не обнаруживается.

Я продолжал вводить эту команду несколько раз: sudo service httpd restart перезагрузить сервер, но не отображаются изменения …

Как я могу это исправить … Я сделал что-то не так?

Решение

Во-первых, обратите внимание, что перезапуск httpd не требуется для файлов .htaccess. Файлы .htaccess специально предназначены для людей, у которых нет root — то есть они не имеют доступа к файлу конфигурации сервера httpd и не могут перезапустить сервер. Поскольку вы можете перезапустить сервер, вам не нужны файлы .htaccess, и вы можете напрямую использовать конфигурацию основного сервера.

Во-вторых, если файлы .htaccess игнорируются, вам необходимо проверить, правильно ли установлен AllowOverride. Увидеть http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride для деталей. Вам также необходимо убедиться, что он установлен в правильной области — то есть в правильном блоке в вашей конфигурации. Будь уверен НЕ редактирование одного в блоке, например.

В-третьих, если вы хотите убедиться, что файл .htaccess действительно читается, поместите в него мусор.
Недопустимая строка, такая как «INVALID LINE HERE», в вашем файле .htaccess приведет к ошибке 500 Server, когда вы укажете браузеру на каталог, содержащий этот файл. Если это не так, то у вас не настроен AllowOverride правильно.

Другие решения

  1. Включить модуль Apache mod_rewrite a2enmod rewrite
  2. добавьте следующий код в /etc/apache2/sites-available/default AllowOverride All
  3. Перезапустите Apache /etc/init.d/apache2 restart

Если вы перепробовали все вышеперечисленное, которые являются действительными и хорошими ответами, и ваш файл htaccess не работает или читается, измените директиву в apache2.conf файл. Под Ubuntu путь /etc/apache2/apache2.conf

Изменить директива, указывающая на ваши общедоступные веб-страницы, где находится файл htaccess. Меняться от AllowOverride None в AllowOverride All

 Options Indexes FollowSymLinks AllowOverride All Require all granted 

За Ubuntu,
Сначала запустите эту команду:

Затем отредактируйте файл /etc/apache2/sites-available/000-default.conf используя nano или vim с помощью этой команды: —

sudo nano /etc/apache2/sites-available/000-default.conf 

Тогда в 000-default.conf файл, добавьте это после строки DocumentRoot /var/www/html , Если ваш корневой каталог html — это что-то другое, то напишите:

Сделав все, перезапустите apache с помощью команды sudo service apache2 restart

Скорее всего, для AllowOverride установлено значение None. в разделе каталога apache2.conf, расположенном в папке / etc / apache2

Попробуйте установить для него AllowOverride All

Пароль будет запрошен. Так что введите свой пароль

  1. Обновите свой 000-default.conf или же default.conf файл находится в / и т.д. / apache2 / сайты-доступны / каталог. Вы не можете редактировать его напрямую. поэтому используйте следующую команду, чтобы открыть sudo gedit /etc/apache2/sites-available/000-default.conf
Читайте также:  Java указать относительный путь

Или же
sudo gedit /etc/apache2/sites-available/default.conf

линия. Добавьте следующий код после него.

 Options Indexes FollowSymLinks AllowOverride All Require all granted 

Сделайте так, чтобы путь тега каталога был таким же, как показано в вашем файле.

По моему опыту, директива / var / www / directory запрещает директивы virtualhost. Так что, если вы перепробовали все предложения и все еще не работали, и вы используете виртуальные хосты, попробуйте это;

1 — убедитесь, что у вас есть
AllowOverride All директива в
/etc/apache2/sites-available/example.com.conf

2 — Проверьте / var / www / Директивы директивы в /etc/apache2/apache2.conf (возможно, в строке 164), которая выглядит так;

 Options Indexes FollowSymLinks AllowOverride None Require all granted 

Если есть AllowOverride None директива изменить его на
AllowOverride All или просто сбежать

По умолчанию Apache запрещает использование файла .htaccess для применения правил перезаписи, поэтому

Шаг 1 — Включение mod_rewrite (если не включено)
Во-первых, нам нужно активировать mod_rewrite. Он доступен, но не включен с чистой установкой Apache 2.

Это активирует модуль или предупредит вас, что модуль уже включен. Чтобы эти изменения вступили в силу, перезапустите Apache.

$ sudo systemctl restart apache2 

mod_rewrite теперь полностью включен. На следующем шаге мы настроим файл .htaccess, который будем использовать для определения правил перезаписи для перенаправлений.

Шаг 2 — Настройка .htaccess
Откройте файл конфигурации Apache по умолчанию, используя nano или ваш любимый текстовый редактор.

$ sudo nano /etc/apache2/sites-available/000-default.conf 

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

  Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted . . . 

Сохраните и закройте файл. Чтобы эти изменения вступили в силу, перезапустите Apache.

$ sudo systemctl restart apache2 

Источник

Support

Find answers, guides, and tutorials to supercharge your content delivery.

.htaccess Not Working — How to Troubleshoot and Fix

.htaccess Not Working - How to Troubleshoot and Fix

Hypertext Access File, most known as .htaccess , is a configuration file for Apache web servers that can be used to define very specific configuration options. Configurations can become quite granular with the use of regex. However, most users typically stick to using popular .htaccess examples, such as redirecting web pages or setting custom headers.

Although .htaccess can be quite useful, it can also be somewhat of a challenge to figure out where the issue lies, given you are faced with an .htaccess not working. This post provides a few tips for helping to resolve this issue by identifying a few common .htaccess problems that you can check in your own .htaccess file, as well as a few troubleshooting techniques.

Common .htaccess problems

The following includes a few common .htaccess problems that are easy to fix and worth trying if you are experiencing issues with your .htaccess file not working.

.htaccess needs to be enabled with AllowOverride

This is the first thing that should be verified. If the AllowOverride directive is set to None , then this will disable all .htaccess files. In order to verify this, you must open the Apache configuration file (typically either called httpd.conf or apache.conf ) and check that the AllowOverride directive is set to AllowOverride All . If you need to make changes to your Apache config, remember to save the file and restart Apache.

Читайте также:  Php datetime format error

The filename is misspelled or does not begin with a period

If you are creating an .htaccess file from scratch (i.e. you are not using a CMS which comes with an .htaccess file included) then you must ensure that the filename is correct and that it begins with a period ( . ). Without the period at the beginning, Apache will ignore the file — the same goes for if the file is misspelled. Additionally, double check that the filename is all lowercase. Your .htaccess file should be named exactly as .htaccess .

The location of your rules needs to be above or below others

Certain .htaccess rules may be sensitive to where they are located within the .htaccess file and therefore cause an .htaccess not working issue. If upon adding an .htaccess rule you notice that it is not taking effect, try moving it above the previous rule or to the very beginning of your file.

Conflicting .htaccess files

Although most users simply use one .htaccess file, you have the ability to use multiple. Since .htaccess file rules apply to the directory that they live in, as well as all other subdirectories, it can happen that two or more .htaccess files are conflicting with one another. To verify this, try disabling each additional .htaccess file you have one-by-one in order to see where the issue is.

Improper syntax being used

It is quite common for a syntax error to be the reason for an .htaccess file not working. If you are familiar with how to read and configure .htaccess rules, double check your configuration. Otherwise, you can use the troubleshooting tips mentioned in the next section to help determine why you are experiencing an issue.

How to troubleshoot .htaccess not working

There are a few options available for troubleshooting an .htaccess not working. Depending upon the type of issue you are trying to solve, you may need to use a combination of the suggestions mentioned below to determine what steps need to be taken to rectify the issue.

Using an .htaccess validator

If you’re having issues with the actual syntax of your .htaccess file, you can run its contents through an .htaccess validator. The following tools will check your syntax and report back any errors that they find.

    .htaccess Check — This first tool gives you two options for validating your .htaccess file. You can either copy and paste the contents of your file directly into the tool or upload an .htaccess file. The tool will then check your syntax and highlight any lines that it finds errors on.

Checking the Apache error log

If upon making changes to your .htaccess file your website breaks, you can also check the Apache error log for additional debugging information. The Apache error log file is typically located in the /var/log/apache2/ directory. Therefore, let’s say for example we have the following content in our .htaccess file.

 RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond % !-f RewriteCond % !-d RewriteRule . /index.php [L] # END WordPress This is some gibberish 

As you can see, I’ve added «This is some gibberish» to intentionally throw an error. Once this file is saved and the page is reloaded, we can check the error logs with the following command.

Читайте также:  Доступ к объектам через php

In this case, Apache throws the following error:

We can use this information to then go back to our .htaccess file and remove or modify any parts of the file that were flagged in the error log.

Debugging with the Apache configuration file

Lastly, you can also debug the content of your .htaccess file by inserting it into your Apache configuration file instead. All of the .htaccess rules will still apply in your configuration file, however now Apache will parse and check the configuration file. Be sure to include all the contents of your .htaccess in the directive. Using the same example as above, the portion of your config file may look similar to the following.

 Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all # BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond % !-f RewriteCond % !-d RewriteRule . /index.php [L] # END WordPress This is gibberish 

Once saved, you can run the following command to check the syntax of your config file.

In this case, Apache returns an error message that says there is a syntax error on line 72 of my configuration file. If you use this method you may also want to verify the error logs in the event that any additional information was recorded there.

Debugging mod_rewrite with logs

If you’re using the Apache mod_rewrite module you can also enable the rewrite log to provide you with more debugging details. To do this, you need to have access to your Apache web server configuration file. Start by opening the configuration file and adding the appropriate directive values as required. For example:

The above snippet will log all mod_rewrite errors up to the «alert» level in your error.log file. Check out Apache’s log level directive to learn more. It should be noted that the higher trace log level you define, the slower this will make your Apache web server.

Summary

.htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren’t comfortable making changes in their web server’s configuration file. Trying to debug .htaccess not working isn’t always the easiest thing to do, however, hopefully by checking the above mentioned .htaccess common problems as well as the troubleshooting tips, you’ll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.

Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Supercharge your content delivery 🚀

Try KeyCDN with a free 14 day trial, no credit card required.

Источник

Оцените статью