Выбрав различные параметры и описав сгенерированный текст в файле .htaccess, вы можете быстро создать файл .htaccess.
Вы также можете генерировать хешированные пароли для обычной аутентификации (.htpasswd).
Что такое файл .htaccess?
Файл установки для управления HTTP-сервером, например Apache.
Такие параметры, как базовая аутентификация, перенаправление и страница ошибки, могут быть установлены для каждого каталога.
Что такое файл .htpasswd?
Он используется для защиты файлов, папок или целых веб-сайтов с использованием аутентификации пользователя HTTP, называемой BASIC-аутентификацией, и реализуется на основе правил, описанных в файле .htaccess.
Информация о пользователе записывается в одной строке для каждого пользователя, и каждая строка содержит имя пользователя и пароль, разделенные двоеточием (:). Имена пользователей хранятся в виде простого текста, но пароли хранятся в хешированной форме.
Вы можете присвоить файлу пароля любое имя, но поскольку Apache по умолчанию использует .htpasswd, а точечные файлы (файлы, начинающиеся с «.») Становятся обычно скрытыми файлами, рекомендуется именовать файл как «.htpasswd».
Часто используемые настройки файлов .htaccess:
- Переписать не-www в www / Удалить www из URL
- Перенаправить http / https
- Перенаправление в файл или каталог
- Кэширование Javascript, CSS или изображений
- Настройка базовой аутентификации
- Настройка предотвращения хотлинков
- Пользовательские страницы ошибок (400 , 404, 500 и т. Д.) Настройка
- Блокировать или разрешать IP-адреса
- Блокировать ботов
- Изменить страницу каталога по умолчанию
- Отказ в доступе. (точка)
- Запретить список каталогов
- Включить gzip
Правила с файлом .htaccess
- .htaccess работает с текущим каталогом и всеми его подпапками.
- Если файл .htaccess не запускается, 500 ошибка возвращается клиенту. Поэтому, пожалуйста, будьте осторожны при редактировании. Перед редактированием рекомендуется сделать копию в качестве резервной копии.
- Используйте «#» перед строкой, которую вы не хотите запускать, чтобы переключить строку в режим комментариев.
Создание htaccess для сайта
Для сайтов работающих на серверах Apache есть возможность настроить свой проект с помощью .htaccess. Этот файл указывает веб-серверу как нужно себя вести в этой папке и ее подкаталогах.
Бесплатно 2 месяц хостинга
по промокоду IKSBIG
Скидка 5% на домен
промокод BC35-3573-8360-EFAB
Автопилот контекстной рекламы
Увеличим заказы из Я.Директ
Реклама
При создании файла Hypertext Access обычно возникают проблемы, которые не дают работать сайту. Большинство ошибок возникает из-за лишних пробелов или отсутствия нужных запятых. По этой причине я решил сделать инструмент, который поможет всем без знаний основ по настройке серверов, создать правильный htaccess для любой CMS.
Что такое .htaccess?
.htaccess (от англ. hypertext access) — файл дополнительной конфигурации веб-сервера Apache, а также подобных ему серверов. Позволяет задавать большое количество дополнительных параметров и разрешений для работы веб-сервера в отдельных каталогах.
Дополнительные варианты перенаправлений
Редирект всех страниц с http:// на https://, в том числе и с http://www на https://
Вариант 1
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Вариант 2
RewriteEngine On
RewriteCond %{HTTPS} =off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]
Вариант 3
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Вариант 4
RewriteEngine On
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Редирект с домена с WWW на домен без WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.site.ru$ [NC]
RewriteRule ^(.*)$ http://site.ru/$1 [R=301,L]
Редирект с домена без WWW на домен с WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^site.ru
RewriteRule (.*) http://www.site.ru/$1 [R=301,L]
Настройка 301 редиректа для сайта
Единственная функция где могут возникнуть проблемы у пользователей. Поэтому я решил описать подробную инструкции. Если вы выполните последовательность, описанную ниже, вы сможете выполнить настройку редиректов правильно.
- Вставляем список старых URL адресов в первое поле (каждый адрес с новой строки).
- Список новых URL вставьте во второе текстовое поле (каждый url с новой строки).
- Нажимаем кнопку «Создать»
- Копируем полученный код и вставляем в свой файл htaccess.
Возможности инструмента
Функционал инструмента включает только самые полезные настройки, которыми пользуюсь сам.
- настройка перенаправления с www, http и с другого домена;
- настройка 301 редиректа;
- установка страниц с ошибками сервера;
- включение отображения ошибок php кода;
- добавление слешей в конец url;
- замена «индексных» страниц (index.php, index.html) на слеш;
- удаление лишних слешей в URL страницы;
- защита интернет-ресурса от спам ссылок.

1. No Vacancy 404
Автор: Riley Shaw
2. Fargo 404
Автор: Nate Watson
Сделано с помощью: HTML CSS
3. 404 No signal
Автор: Adem ilter
4. 404 Page
Автор: Kasper De Bruyne
5. Yeti 404 Page
Автор: Darin
6. Error 404
Автор: Swarup Kumar Kuila
7. Only CSS: 404 Rolling Box
Автор: Yusuke Nakaya
8. 404 page
Автор: Naved khan
9. Ghost Page | 404
Автор: Diogo Gomes
10. Space 404
Автор: Jared Rowe
Анимированный SVG для страницы 404 на Vecteezy.com
11. 404 Error page
Автор: Vineeth.TR
Страница ошибки в Pure css :), вдохновленная Bons 404
12. My Error 404 Page
Автор: Taufik Nurrohman
13. code for fun (day02): страница с ошибкой 404, режим пещерного человека — чистый CSS
Автор: Sergio
Еще больше подобных шаблонов можно найти по тут
nginx |
Apache HTTPD |
Lighttpd |
express.js |
koa.js |
Caddy |
Customization
Simple HttpErrorPages
Simple HTTP Error Page Generator. Create a bunch of custom error pages — suitable to use with Lighttpd, Nginx, expressjs, koajs ,Apache-Httpd or any other Webserver.
Features
- Static pages (for webservers)
- Multi-Language (i18n) support
- Generator script to customize pages
- Native express.js middleware
- Native koa.js middleware
Demo
- HTTP400
- HTTP401
- HTTP403
- HTTP404
- HTTP500
- HTTP501
- HTTP502
- HTTP503
- HTTP520
- HTTP521
Download
Just clone/download the git repository or use the prebuild packages (only the generated html files are included)
Download Prebuild Packages (Pages only, en_US)
- Download Single Files
NGINX Integration
NGINX supports custom error-pages using multiple error_page directives.
File: default.conf
Example — assumes HttpErrorPages are located into /var/ErrorPages/.
server { listen 80; server_name localhost; root /var/www; index index.html; location / { try_files $uri $uri/ =404; # add one directive for each http status code error_page 400 /ErrorPages/HTTP400.html; error_page 401 /ErrorPages/HTTP401.html; error_page 402 /ErrorPages/HTTP402.html; error_page 403 /ErrorPages/HTTP403.html; error_page 404 /ErrorPages/HTTP404.html; error_page 500 /ErrorPages/HTTP500.html; error_page 501 /ErrorPages/HTTP501.html; error_page 502 /ErrorPages/HTTP502.html; error_page 503 /ErrorPages/HTTP503.html; } # redirect the virtual ErrorPages path the real path location /ErrorPages/ { alias /var/ErrorPages/; internal; }
Apache Httpd Integration
Apache Httpd 2.x supports custom error-pages using multiple ErrorDocument directives.
File: httpd.conf or .htaccess
Example — assumes HttpErrorPages are located into your document root /var/www/...docroot../ErrorPages.
ErrorDocument 400 /ErrorPages/HTTP400.html ErrorDocument 401 /ErrorPages/HTTP401.html ErrorDocument 403 /ErrorPages/HTTP403.html ErrorDocument 404 /ErrorPages/HTTP404.html ErrorDocument 500 /ErrorPages/HTTP500.html ErrorDocument 501 /ErrorPages/HTTP501.html ErrorDocument 502 /ErrorPages/HTTP502.html ErrorDocument 503 /ErrorPages/HTTP503.html
Lighttpd Integration
Lighttpd supports custom error-pages using the server.errorfile-prefix directive.
File: lighttpd.conf
Example — assumes HttpErrorPages are located into /var/www/ErrorPages/.
server.errorfile-prefix = "/var/www/ErrorPages/HTTP"
expressjs Integration
HttpErrorPages are available as NPM-Package — just install http-error-pages via npm/yarn
Installation
yarn add http-error-pages
Example
A ready-to-use example can be found in examples/express.js
const _express = require('express'); const _webapp = _express(); const _httpErrorPages = require('http-error-pages'); async function bootstrap(){ // demo handler _webapp.get('/', function(req, res){ res.type('.txt').send('HttpErrorPages Demo'); }); // throw an 403 error _webapp.get('/my403error', function(req, res, next){ const myError = new Error(); myError.status = 403; next(myError); }); // throw an internal error _webapp.get('/500', function(req, res){ throw new Error('Server Error'); }); // use http error pages handler (final statement!) // because of the asynchronous file-loaders, wait until it has been executed await _httpErrorPages.express(_webapp, { lang: 'en_US', payload: { footer: 'Hello <strong>World</strong>', myvar: 'hello world' } }); // start service _webapp.listen(8888); } // invoke bootstrap operation bootstrap() .then(function(){ console.log('Running Demo on Port 8888'); }) .catch(function(e){ console.error(e); });
Options
Syntax: Promise _httpErrorPages.express(expressWebapp [, options:Object])
template(type:string) — the path to a custom EJS template used to generate the pages. default assets/template.ejscss(type:string) — the path to a precompiled CSS file injected into the page. default assets/layout.csslang(type:string) — language definition which should be used (available in thei18n/directory). default en_USpayload(type:object) — additional variables available within the templatepayload.footer(type:string) — optional page footer content (html allowed). default nullfilter(type:function) — filter callback to manipulate the variables before populated within the templateonError(type:function) — simple debug handler to print errors to the console (not to be used in production!)
koajs Integration
HttpErrorPages are available as NPM-Package — just install http-error-pages via npm/yarn
Installation
yarn add http-error-pages
Example
A ready-to-use example can be found in examples/koa.js.
Keep in mind that the following example has to be executed within an async context!
const _koa = require('koa'); const _webapp = new _koa(); const _httpErrorPages = require('http-error-pages'); // use http error pages handler (INITIAL statement!) // because of the asynchronous file-loaders, wait until it has been executed - it returns an async handler _webapp.use(await _httpErrorPages.koa({ lang: 'en_US', payload: { footer: 'Hello <strong>World</strong>', myvar: 'hello world' } })); // add other middleware handlers _webapp.use(async (ctx, next) => { if (ctx.path == '/'){ ctx.type = 'text'; ctx.body = 'HttpErrorPages Demo'; }else{ return next(); } }); // start service _webapp.listen(8888);
Options
Syntax: Promise _httpErrorPages.koa([options:Object])
template(type:string) — the path to a custom EJS template used to generate the pages. default assets/template.ejscss(type:string) — the path to a precompiled CSS file injected into the page. default assets/layout.csslang(type:string) — language definition which should be used (available in thei18n/directory). default en_USpayload(type:object) — additional variables available within the templatepayload.footer(type:string) — optional page footer content (html allowed). default nullfilter(type:function) — filter callback to manipulate the variables before populated within the templateonError(type:function) — simple debug handler to print errors to the console (not to be used in production!)
Caddy Integration
Caddy supports custom error-pages using errors directive.
File: Caddyfile
Example — assumes HttpErrorPages are located into /var/www/error.
www.yoursite.com {
// Other configurations
errors {
404 /var/www/error/HTTP404.html
}
// Other configurations
}
Customization
First of all, clone
or download the http-error-pages repository.
Install Dependencies
You have to install the node dev dependencies to build the pages:
# run the yarn command within the cloned repository yarn install # or if you more familiar with npm.. npm install
To customize the pages, you can edit any of the template files and finally run the generator-script.
All generated html files are located into the dist/ directory by default.
If you wan’t to add custom pages/additional error-codes, just put a new entry into the i18n/pages-en_US.json file (its recommended to copy the file).
The generator-script will process each entry and generates an own page.
Files
- config.json — basic configuration options
- assets/layout.scss — the SCSS based styles
- assets/template.ejs — the EJS based page template
- i18n/pages-.json — the page definitions (multilanguage)
- dist/*.html — generator output directory
Change page styles
To modify the page styles, just edit the SCSS based layout assets/layout.scss and finally run gulp to generate the css code.
The new layout file is stored in assets/layout.css — run the page generator to create the pages.
Example
# start gulp sccs via npm $ npm run gulp > http-error-pages@0.6.0 gulp HttpErrorPages > gulp [08:40:33] Using gulpfile HttpErrorPages/gulpfile.js [08:40:33] Starting 'sass'... [08:40:34] Finished 'sass' after 108 ms [08:40:34] Starting 'default'... [08:40:34] Finished 'default' after 40 μs # generate http-error-pages using modified stylesheet $ npm run static > http-error-pages@0.6.0 static HttpErrorPages > node bin/generator.js static Paths |- Config: HttpErrorPages/config.json |- Template: HttpErrorPages/assets/template.ejs |- Styles: HttpErrorPages/assets/layout.css |- Pages: HttpErrorPages/i18n/pages-en_US.json Generating static pages |- Page <HTTP404.html> |- Page <HTTP403.html> |- Page <HTTP400.html> |- Page <HTTP500.html> |- Page <HTTP501.html> |- Page <HTTP502.html> |- Page <HTTP520.html> |- Page <HTTP503.html> |- Page <HTTP521.html> |- Page <HTTP533.html> |- Page <HTTP401.html> Static files generated
Multi language (i18n)
To use a different language just provide a custom page definition — in case the file is located in i18n you can use the --lang option
Example
$ npm run static -- --lang pt_BR
> http-error-pages@0.6.0 static HttpErrorPages
> node bin/generator.js static "--lang" "pt_BR"
Paths
|- Config: HttpErrorPages/config.json
|- Template: HttpErrorPages/assets/template.ejs
|- Styles: HttpErrorPages/assets/layout.css
|- Pages: HttpErrorPages/i18n/pages-pt_BR.json
Generating static pages
|- Page <HTTP404.html>
|- Page <HTTP400.html>
|- Page <HTTP401.html>
|- Page <HTTP403.html>
|- Page <HTTP500.html>
|- Page <HTTP501.html>
|- Page <HTTP502.html>
|- Page <HTTP520.html>
|- Page <HTTP503.html>
|- Page <HTTP521.html>
|- Page <HTTP533.html>
Static files generated
Add custom pages
Create custom error codes/pages used by e.g. CloudFlare
Example
// webserver origin error "520": { "title": "Origin Error - Unknown Host", "message": "The requested hostname is not routed. Use only hostnames to access resources." }, // webserver down error "521": { "title": "Webservice currently unavailable", "message": "We've got some trouble with our backend upstream cluster.nOur service team has been dispatched to bring it back online." },
Change footer message
The footer message can easily be changed/removed by editing config.json.
Example — customm footer
{ // Output Filename Scheme - eg. HTTP500.html "scheme": "HTTP%code%.html", // Footer content (HTML Allowed) "footer": "Contact <a href="mailto:info@example.org">info@example.org</a>" }
Example — no footer
{ // Output Filename Scheme - eg. HTTP500.html "scheme": "HTTP%code%.html" }
Placeholders/Variables
The following set of variables is exposed to the ejs template (404 page example):
{ title: 'Resource not found', message: 'The requested resource could not be found but may be available again in the future.', code: '404', language: 'en', scheme: 'HTTP%code%.html', pagetitle: "We've got some trouble | %code% - %title%", footer: 'Tech Contact <a href="mailto:info@example.org">info@example.org</a>', myvar: 'Hello World' }
To generate dynamic titles/content based on the current variable set, each variable is exposed as placeholder (surrounded by %).
You can also define custom variable within the page definitions, everything is merged togehter.
Modify the HTML template
The HTML template is based on ejs and located in assets/template.ejs — you can apply any kind of changes.
<!DOCTYPE html> <html lang="<%= vars.language %>"> <head> <!-- Simple HttpErrorPages | MIT License | https://github.com/HttpErrorPages --> <meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1" /> <title><%= vars.pagetitle %></title> <style type="text/css"><%- vars.inlinecss %></style> </head> <body> <div class="cover"><h1><%= vars.title %> <small><%= vars.code %></small></h1><p class="lead"><%= vars.message %></p></div> <% if (vars.footer){ %><footer><p><%- vars.footer %></p></footer><% } %> </body> </html>
Command line options
The http-error-pages generator allows you to use custom template/config files directly. This is the recommended method to create full-customized pages.
$ npm run static -- --help
> http-error-pages@0.6.0 static HttpErrorPages
> node bin/generator.js static "--help"
Usage: static [options] [config]
run http-error-pages generator
Options:
-t, --template <path> path to your custom EJS template file
-s, --styles <path> path to your custom stylesheet (precompiled as CSS!)
-p, --pages <path> path to your custom page definition
-l, --lang <lang> the language of the default page definition
-o, --out <path> output directory
-h, --help output usage information
Example — use custom files
We assume you’ve created a folder named example_org which contains all relevant template files
# via npm run-script (cross platform) $ npm run static -- -t example_org/template.ejs -s example_org/styles.css -p example_org/pages.json -o example_org/output # .. or directly (linux only) $ http-error-pages -t example_org/template.ejs -s example_org/styles.css -p example_org/pages.json -o example_org/output
License
HttpErrorsPages is OpenSource and licensed under the Terms of The MIT License (X11) — your’re welcome to contribute
nginx |
Apache HTTPD |
Lighttpd |
express.js |
koa.js |
Caddy |
Customization
Simple HttpErrorPages
Simple HTTP Error Page Generator. Create a bunch of custom error pages — suitable to use with Lighttpd, Nginx, expressjs, koajs ,Apache-Httpd or any other Webserver.
Features
- Static pages (for webservers)
- Multi-Language (i18n) support
- Generator script to customize pages
- Native express.js middleware
- Native koa.js middleware
Demo
- HTTP400
- HTTP401
- HTTP403
- HTTP404
- HTTP500
- HTTP501
- HTTP502
- HTTP503
- HTTP520
- HTTP521
Download
Just clone/download the git repository or use the prebuild packages (only the generated html files are included)
Download Prebuild Packages (Pages only, en_US)
- Download Single Files
NGINX Integration
NGINX supports custom error-pages using multiple error_page directives.
File: default.conf
Example — assumes HttpErrorPages are located into /var/ErrorPages/.
server { listen 80; server_name localhost; root /var/www; index index.html; location / { try_files $uri $uri/ =404; # add one directive for each http status code error_page 400 /ErrorPages/HTTP400.html; error_page 401 /ErrorPages/HTTP401.html; error_page 402 /ErrorPages/HTTP402.html; error_page 403 /ErrorPages/HTTP403.html; error_page 404 /ErrorPages/HTTP404.html; error_page 500 /ErrorPages/HTTP500.html; error_page 501 /ErrorPages/HTTP501.html; error_page 502 /ErrorPages/HTTP502.html; error_page 503 /ErrorPages/HTTP503.html; } # redirect the virtual ErrorPages path the real path location /ErrorPages/ { alias /var/ErrorPages/; internal; }
Apache Httpd Integration
Apache Httpd 2.x supports custom error-pages using multiple ErrorDocument directives.
File: httpd.conf or .htaccess
Example — assumes HttpErrorPages are located into your document root /var/www/...docroot../ErrorPages.
ErrorDocument 400 /ErrorPages/HTTP400.html ErrorDocument 401 /ErrorPages/HTTP401.html ErrorDocument 403 /ErrorPages/HTTP403.html ErrorDocument 404 /ErrorPages/HTTP404.html ErrorDocument 500 /ErrorPages/HTTP500.html ErrorDocument 501 /ErrorPages/HTTP501.html ErrorDocument 502 /ErrorPages/HTTP502.html ErrorDocument 503 /ErrorPages/HTTP503.html
Lighttpd Integration
Lighttpd supports custom error-pages using the server.errorfile-prefix directive.
File: lighttpd.conf
Example — assumes HttpErrorPages are located into /var/www/ErrorPages/.
server.errorfile-prefix = "/var/www/ErrorPages/HTTP"
expressjs Integration
HttpErrorPages are available as NPM-Package — just install http-error-pages via npm/yarn
Installation
yarn add http-error-pages
Example
A ready-to-use example can be found in examples/express.js
const _express = require('express'); const _webapp = _express(); const _httpErrorPages = require('http-error-pages'); async function bootstrap(){ // demo handler _webapp.get('/', function(req, res){ res.type('.txt').send('HttpErrorPages Demo'); }); // throw an 403 error _webapp.get('/my403error', function(req, res, next){ const myError = new Error(); myError.status = 403; next(myError); }); // throw an internal error _webapp.get('/500', function(req, res){ throw new Error('Server Error'); }); // use http error pages handler (final statement!) // because of the asynchronous file-loaders, wait until it has been executed await _httpErrorPages.express(_webapp, { lang: 'en_US', payload: { footer: 'Hello <strong>World</strong>', myvar: 'hello world' } }); // start service _webapp.listen(8888); } // invoke bootstrap operation bootstrap() .then(function(){ console.log('Running Demo on Port 8888'); }) .catch(function(e){ console.error(e); });
Options
Syntax: Promise _httpErrorPages.express(expressWebapp [, options:Object])
template(type:string) — the path to a custom EJS template used to generate the pages. default assets/template.ejscss(type:string) — the path to a precompiled CSS file injected into the page. default assets/layout.csslang(type:string) — language definition which should be used (available in thei18n/directory). default en_USpayload(type:object) — additional variables available within the templatepayload.footer(type:string) — optional page footer content (html allowed). default nullfilter(type:function) — filter callback to manipulate the variables before populated within the templateonError(type:function) — simple debug handler to print errors to the console (not to be used in production!)
koajs Integration
HttpErrorPages are available as NPM-Package — just install http-error-pages via npm/yarn
Installation
yarn add http-error-pages
Example
A ready-to-use example can be found in examples/koa.js.
Keep in mind that the following example has to be executed within an async context!
const _koa = require('koa'); const _webapp = new _koa(); const _httpErrorPages = require('http-error-pages'); // use http error pages handler (INITIAL statement!) // because of the asynchronous file-loaders, wait until it has been executed - it returns an async handler _webapp.use(await _httpErrorPages.koa({ lang: 'en_US', payload: { footer: 'Hello <strong>World</strong>', myvar: 'hello world' } })); // add other middleware handlers _webapp.use(async (ctx, next) => { if (ctx.path == '/'){ ctx.type = 'text'; ctx.body = 'HttpErrorPages Demo'; }else{ return next(); } }); // start service _webapp.listen(8888);
Options
Syntax: Promise _httpErrorPages.koa([options:Object])
template(type:string) — the path to a custom EJS template used to generate the pages. default assets/template.ejscss(type:string) — the path to a precompiled CSS file injected into the page. default assets/layout.csslang(type:string) — language definition which should be used (available in thei18n/directory). default en_USpayload(type:object) — additional variables available within the templatepayload.footer(type:string) — optional page footer content (html allowed). default nullfilter(type:function) — filter callback to manipulate the variables before populated within the templateonError(type:function) — simple debug handler to print errors to the console (not to be used in production!)
Caddy Integration
Caddy supports custom error-pages using errors directive.
File: Caddyfile
Example — assumes HttpErrorPages are located into /var/www/error.
www.yoursite.com {
// Other configurations
errors {
404 /var/www/error/HTTP404.html
}
// Other configurations
}
Customization
First of all, clone
or download the http-error-pages repository.
Install Dependencies
You have to install the node dev dependencies to build the pages:
# run the yarn command within the cloned repository yarn install # or if you more familiar with npm.. npm install
To customize the pages, you can edit any of the template files and finally run the generator-script.
All generated html files are located into the dist/ directory by default.
If you wan’t to add custom pages/additional error-codes, just put a new entry into the i18n/pages-en_US.json file (its recommended to copy the file).
The generator-script will process each entry and generates an own page.
Files
- config.json — basic configuration options
- assets/layout.scss — the SCSS based styles
- assets/template.ejs — the EJS based page template
- i18n/pages-.json — the page definitions (multilanguage)
- dist/*.html — generator output directory
Change page styles
To modify the page styles, just edit the SCSS based layout assets/layout.scss and finally run gulp to generate the css code.
The new layout file is stored in assets/layout.css — run the page generator to create the pages.
Example
# start gulp sccs via npm $ npm run gulp > http-error-pages@0.6.0 gulp HttpErrorPages > gulp [08:40:33] Using gulpfile HttpErrorPages/gulpfile.js [08:40:33] Starting 'sass'... [08:40:34] Finished 'sass' after 108 ms [08:40:34] Starting 'default'... [08:40:34] Finished 'default' after 40 μs # generate http-error-pages using modified stylesheet $ npm run static > http-error-pages@0.6.0 static HttpErrorPages > node bin/generator.js static Paths |- Config: HttpErrorPages/config.json |- Template: HttpErrorPages/assets/template.ejs |- Styles: HttpErrorPages/assets/layout.css |- Pages: HttpErrorPages/i18n/pages-en_US.json Generating static pages |- Page <HTTP404.html> |- Page <HTTP403.html> |- Page <HTTP400.html> |- Page <HTTP500.html> |- Page <HTTP501.html> |- Page <HTTP502.html> |- Page <HTTP520.html> |- Page <HTTP503.html> |- Page <HTTP521.html> |- Page <HTTP533.html> |- Page <HTTP401.html> Static files generated
Multi language (i18n)
To use a different language just provide a custom page definition — in case the file is located in i18n you can use the --lang option
Example
$ npm run static -- --lang pt_BR
> http-error-pages@0.6.0 static HttpErrorPages
> node bin/generator.js static "--lang" "pt_BR"
Paths
|- Config: HttpErrorPages/config.json
|- Template: HttpErrorPages/assets/template.ejs
|- Styles: HttpErrorPages/assets/layout.css
|- Pages: HttpErrorPages/i18n/pages-pt_BR.json
Generating static pages
|- Page <HTTP404.html>
|- Page <HTTP400.html>
|- Page <HTTP401.html>
|- Page <HTTP403.html>
|- Page <HTTP500.html>
|- Page <HTTP501.html>
|- Page <HTTP502.html>
|- Page <HTTP520.html>
|- Page <HTTP503.html>
|- Page <HTTP521.html>
|- Page <HTTP533.html>
Static files generated
Add custom pages
Create custom error codes/pages used by e.g. CloudFlare
Example
// webserver origin error "520": { "title": "Origin Error - Unknown Host", "message": "The requested hostname is not routed. Use only hostnames to access resources." }, // webserver down error "521": { "title": "Webservice currently unavailable", "message": "We've got some trouble with our backend upstream cluster.nOur service team has been dispatched to bring it back online." },
Change footer message
The footer message can easily be changed/removed by editing config.json.
Example — customm footer
{ // Output Filename Scheme - eg. HTTP500.html "scheme": "HTTP%code%.html", // Footer content (HTML Allowed) "footer": "Contact <a href="mailto:info@example.org">info@example.org</a>" }
Example — no footer
{ // Output Filename Scheme - eg. HTTP500.html "scheme": "HTTP%code%.html" }
Placeholders/Variables
The following set of variables is exposed to the ejs template (404 page example):
{ title: 'Resource not found', message: 'The requested resource could not be found but may be available again in the future.', code: '404', language: 'en', scheme: 'HTTP%code%.html', pagetitle: "We've got some trouble | %code% - %title%", footer: 'Tech Contact <a href="mailto:info@example.org">info@example.org</a>', myvar: 'Hello World' }
To generate dynamic titles/content based on the current variable set, each variable is exposed as placeholder (surrounded by %).
You can also define custom variable within the page definitions, everything is merged togehter.
Modify the HTML template
The HTML template is based on ejs and located in assets/template.ejs — you can apply any kind of changes.
<!DOCTYPE html> <html lang="<%= vars.language %>"> <head> <!-- Simple HttpErrorPages | MIT License | https://github.com/HttpErrorPages --> <meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1" /> <title><%= vars.pagetitle %></title> <style type="text/css"><%- vars.inlinecss %></style> </head> <body> <div class="cover"><h1><%= vars.title %> <small><%= vars.code %></small></h1><p class="lead"><%= vars.message %></p></div> <% if (vars.footer){ %><footer><p><%- vars.footer %></p></footer><% } %> </body> </html>
Command line options
The http-error-pages generator allows you to use custom template/config files directly. This is the recommended method to create full-customized pages.
$ npm run static -- --help
> http-error-pages@0.6.0 static HttpErrorPages
> node bin/generator.js static "--help"
Usage: static [options] [config]
run http-error-pages generator
Options:
-t, --template <path> path to your custom EJS template file
-s, --styles <path> path to your custom stylesheet (precompiled as CSS!)
-p, --pages <path> path to your custom page definition
-l, --lang <lang> the language of the default page definition
-o, --out <path> output directory
-h, --help output usage information
Example — use custom files
We assume you’ve created a folder named example_org which contains all relevant template files
# via npm run-script (cross platform) $ npm run static -- -t example_org/template.ejs -s example_org/styles.css -p example_org/pages.json -o example_org/output # .. or directly (linux only) $ http-error-pages -t example_org/template.ejs -s example_org/styles.css -p example_org/pages.json -o example_org/output
License
HttpErrorsPages is OpenSource and licensed under the Terms of The MIT License (X11) — your’re welcome to contribute



