NGINX

Daemons of BSD
Ответить
madhammer
Администратор
Сообщения: 41
Зарегистрирован: 21 мар 2019, 15:01

NGINX

Сообщение madhammer »

nginx.conf

Код: Выделить всё

user  www;
worker_processes  1;
error_log  /var/log/nginx/error.log;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
....
#    access_log  logs/access.log  main;
....
gzip on;
gzip_static on;
gzip_vary on;
gzip_http_version 1.1;
gzip_min_length 700;
gzip_comp_level 6;
ssl_session_cache   shared:SSL:10m;
ssl_session_timeout 5m;
ssl_prefer_server_ciphers on;
ssl_stapling on;
resolver 127.0.0.1;

    sendfile        on;

    keepalive_timeout  65;

    #gzip  on;



server {
    listen       443  ssl;
    server_name  www.xammep.net;
.....
    access_log /var/log/nginx/www.xammep.net-access.log;
    error_log /var/log/nginx/www.xammep.net-error.log;

    keepalive_timeout   60;

    ssl_certificate      /usr/local/etc/letsencrypt/live/xammep.net/cert.pem;
    ssl_certificate_key  /usr/local/etc/letsencrypt/live/xammep.net/privkey.pem;
    ssl_trusted_certificate /usr/local/etc/letsencrypt/live/xammep.net/fullchain.pem;
....
....
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers  "HIGH:!RC4:!aNULL:!MD5:!kEDH";
    add_header Strict-Transport-Security 'max-age=604800';


            root   /usr/local/www/www.xammep.net;
            index  resume.php;

        location / {
                # add_header Access-Control-Allow-Origin *;
                try_files $uri $uri/ /index.php?$query_string;
        }

...
    location ~* \.php$ {
    fastcgi_index   resume.php;
    fastcgi_pass   unix:/tmp/php-fpm.sock;
    include         fastcgi_params;
    fastcgi_param   HTTPS on;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;


     }
   }
...
madhammer
Администратор
Сообщения: 41
Зарегистрирован: 21 мар 2019, 15:01

Re: NGINX

Сообщение madhammer »

htpasswd для nginx на питоне

Код: Выделить всё

#!/usr/local/bin/python2.7
"""Replacement for htpasswd"""
# Original author: Eli Carter

import os
import sys
import random
from optparse import OptionParser

# We need a crypt module, but Windows doesn't have one by default.  Try to find
# one, and tell the user if we can't.
try:
    import crypt
except ImportError:
    try:
        import fcrypt as crypt
    except ImportError:
        sys.stderr.write("Cannot find a crypt module.  "
                         "Possibly http://carey.geek.nz/code/python-fcrypt/\n")
        sys.exit(1)


def salt():
    """Returns a string of 2 randome letters"""
    letters = 'abcdefghijklmnopqrstuvwxyz' \
              'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
              '0123456789/.'
    return random.choice(letters) + random.choice(letters)


class HtpasswdFile:
    """A class for manipulating htpasswd files."""

    def __init__(self, filename, create=False):
        self.entries = []
        self.filename = filename
        if not create:
            if os.path.exists(self.filename):
                self.load()
            else:
                raise Exception("%s does not exist" % self.filename)

    def load(self):
        """Read the htpasswd file into memory."""
        lines = open(self.filename, 'r').readlines()
        self.entries = []
        for line in lines:
            username, pwhash = line.split(':')
            entry = [username, pwhash.rstrip()]
            self.entries.append(entry)

    def save(self):
        """Write the htpasswd file to disk"""
        open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1])
                                             for entry in self.entries])

    def update(self, username, password):
        """Replace the entry for the given user, or add it if new."""
        pwhash = crypt.crypt(password, salt())
        matching_entries = [entry for entry in self.entries
                            if entry[0] == username]
        if matching_entries:
            matching_entries[0][1] = pwhash
        else:
            self.entries.append([username, pwhash])

    def delete(self, username):
        """Remove the entry for the given user."""
        self.entries = [entry for entry in self.entries
                        if entry[0] != username]


def main():
    """%prog [-c] -b filename username password
    Create or update an htpasswd file"""
    # For now, we only care about the use cases that affect tests/functional.py
    parser = OptionParser(usage=main.__doc__)
    parser.add_option('-b', action='store_true', dest='batch', default=False,
        help='Batch mode; password is passed on the command line IN THE CLEAR.'
        )
    parser.add_option('-c', action='store_true', dest='create', default=False,
        help='Create a new htpasswd file, overwriting any existing file.')
    parser.add_option('-D', action='store_true', dest='delete_user',
        default=False, help='Remove the given user from the password file.')

    options, args = parser.parse_args()

    def syntax_error(msg):
        """Utility function for displaying fatal error messages with usage
        help.
        """
        sys.stderr.write("Syntax error: " + msg)
        sys.stderr.write(parser.get_usage())
        sys.exit(1)

    if not options.batch:
        syntax_error("Only batch mode is supported\n")

    # Non-option arguments
    if len(args) < 2:
        syntax_error("Insufficient number of arguments.\n")
    filename, username = args[:2]
    if options.delete_user:
        if len(args) != 2:
            syntax_error("Incorrect number of arguments.\n")
        password = None
    else:
        if len(args) != 3:
            syntax_error("Incorrect number of arguments.\n")
        password = args[2]

    passwdfile = HtpasswdFile(filename, create=options.create)

    if options.delete_user:
        passwdfile.delete(username)
    else:
        passwdfile.update(username, password)

    passwdfile.save()


if __name__ == '__main__':
    main()
Пользовать так:
htpasswd.py -c -b /usr/local/nginx/.htpasswd username password - создает файл (.htpasswd) и добавляет пользователя (если файл есть, он затирается)
htpasswd.py -b /usr/local/nginx/.htpasswd username password - просто добавляет пользователя
madhammer
Администратор
Сообщения: 41
Зарегистрирован: 21 мар 2019, 15:01

Re: NGINX

Сообщение madhammer »

Настройка robots.txt

Код: Выделить всё

User-agent: *
Allow: /
Disallow: /.well-known
Disallow: /images



User-agent: Yandex
Allow: /
Disallow: /.well-known
Disallow: /images

User-agent: Googlebot
Allow: /
Disallow: /.well-known
Disallow: /images


Host: www.xammep.net
Sitemap: https://www.xammep.net/sitemap.xml
sitemap.xml

Код: Выделить всё

<urlset xmlns="http://www.xammep.net">
 <url>
  <loc>http://www.xammep.net/</loc>
  <lastmod>2019-04-15T18:54:13+05:00</lastmod>
  <changefreq>always</changefreq>
  <priority>1.0</priority>
 </url>
</urlset>
favicon.ico - любая иконка. Либо создать пустой файл, дабы в логах не отстреливало.
Ответить