草庐IT

nginx配置用户认证、域名跳转、日志记录、静态文件缓存、防盗链

模范生 2023-03-28 原文
一、nginx配置用户认证

首先需要安装apache,可以使用yum install httpd 安装;或者在其他机器创建好.htpasswd文件,拷贝到服务器;

创建用户,并生成密码文件:

/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/.htpasswd  test 

// 添加test用户,第一次添加时需要加-c参数,第二次添加时不需要-c参数;


访问指定目录配置用户认证:

在nginx的default配置文件中添加,红色的部分是指定在哪个目录设置用户认证。

location  /a/ {

         auth_basic              "Auth";

         auth_basic_user_file   /usr/local/nginx/conf/.htpasswd;

}


实验测试,使用curl 解析/a/目录下的index.html为401未认证;使用-u 用户名密码登录之后为200 OK;

[root@localhost vhosts]# curl -x127.0.0.1:80 192.168.20.30/a/index.html -I HTTP/1.1 401 Unauthorized Server: nginx/1.6.2 Date: Thu, 14 May 2015 09:48:18 GMT Content-Type: text/html Content-Length: 194 Connection: keep-alive WWW-Authenticate: Basic realm="Auth" [root@localhost vhosts]# curl -utest:1234 -x127.0.0.1:80 192.168.20.30/a/index.html -I HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Thu, 14 May 2015 09:48:26 GMT Content-Type: text/html Content-Length: 612 Last-Modified: Thu, 14 May 2015 09:27:34 GMT Connection: keep-alive ETag: "55546a86-264" Accept-Ranges: bytes

访问admin.php后台,设置用户认证;设置认证的代码要写在匹配php的前面,并且也要加入解析php的代码;

[root@localhost vhosts]# cat default.conf  server {     listen 80 default;     server_name localhost;     index index.html index.htm index.php;     root /usr/local/nginx/html;          location ~ admin\.php {         auth_basic              "Auth";         auth_basic_user_file   /usr/local/nginx/conf/.htpasswd;         include fastcgi_params;         fastcgi_pass unix:/tmp/php-fcgi.sock;         fastcgi_index index.php;         fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;     }     location ~ \.php$ {         include fastcgi_params;         fastcgi_pass unix:/tmp/php-fcgi.sock;         fastcgi_index index.php;         fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;     } }

网页测试登录admin.php页面弹出认证对话框,输入用户名密码才可以访问。


如不指定root目录,直接使用认证的话,打开首页弹出对话框进行认证;

    location / {

        auth_basic              "Auth";

        auth_basic_user_file   /usr/local/nginx/conf/.htpasswd;



二、配置域名重定向

nginx默认虚拟主机配置加入下面的代码:

    server_name 11.com 22.com www.111.com;


    if ($host != 'www.111.com' ) {
        rewrite  ^/(.*)$  http://www.111.com/$1  permanent;

    }

permanent    永久重定向301;


试验测试:访问11.com 22.com 都会跳转到location:www.111.com;

[root@localhost vhosts]# curl -x127.0.0.1:80 11.com -I HTTP/1.1 301 Moved Permanently Server: nginx/1.6.2 Date: Thu, 14 May 2015 22:15:16 GMT Content-Type: text/html Content-Length: 184 Connection: keep-alive Location: http://www.111.com/ [root@localhost vhosts]# curl -x127.0.0.1:80 22.com -I HTTP/1.1 301 Moved Permanently Server: nginx/1.6.2 Date: Thu, 14 May 2015 22:15:21 GMT Content-Type: text/html Content-Length: 184 Connection: keep-alive Location: http://www.111.com/

三、配置日志记录

日志格式,main为定义的日志格式名;日志格式需加入到nginx.conf主配置文件http段中;

log_format main '$remote_addr - $remote_user [$time_local] $request '

                    '"$status" $body_bytes_sent "$http_referer" '

                    '"$http_user_agent" "$http_x_forwarded_for"';

log_format main1 '$proxy_add_x_forwarded_for - $remote_user [$time_local] '

                      '"$request" $status $body_bytes_sent '

                      '"$http_referer" "$http_user_agent"';  

//此日志格式为,ip不仅记录代理的ip还记录远程客户端真实IP。


添加访问日志的格式,写到default.conf最后一行;

server {     listen 80 default;     server_name localhost;     index index.html index.htm index.php;     root /usr/local/nginx/html;          location ~ \.php$ {     include fastcgi_params;     fastcgi_pass unix:/tmp/php-fcgi.sock;     fastcgi_index index.php;     fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;     }     access_log /home/logs/xxx.log combined_realip; }combined_realip为nginx.conf 定义的日志格式的名字。


使用curl测试之后,产生新的log;

[root@localhost vhosts]# curl -x127.0.0.1:80 192.168.20.30/index.html -I [root@localhost vhosts]# cat /home/logs/xxx.log  127.0.0.1 - [15/May/2015:15:13:49 +0800]192.168.20.30 "/index.html" 200"-" "curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2"错误日志error_log日志级别:

error_log 级别分为 debug, info, notice, warn, error, crit  默认为crit, 该级别在日志名后边定义格式如下:error_log  /your/path/error.log crit;  

crit 记录的日志最少,而debug记录的日志最多。如果你的nginx遇到一些问题,比如502比较频繁出现,但是看默认的error_log并没有看到有意义的信息,那么就可以调一下错误日志的级别,当你调成error级别时,错误日志记录的内容会更加丰富。



四、静态文件(图片、flash、js、css)不记录日志,并配置缓存;

   location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

        {

         expires    30d;

         access_log off;

        }

    location ~ .*\.(js|css)?$ 

        {

         expires    12h;

         access_log off;

        }

expires      定义缓存时间;

access_log off 不记录日志;

试验测试:touch 1.jpg 2.js文件,使用curl测试cache-control为缓存时间

[root@localhost vhosts]# touch /usr/local/nginx/html/1.jpg[root@localhost vhosts]# curl -x127.0.0.1:80 www.111.com/1.jpg -I HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Thu, 14 May 2015 22:11:45 GMT Content-Type: p_w_picpath/jpeg Content-Length: 0 Last-Modified: Thu, 14 May 2015 22:11:41 GMT Connection: keep-alive ETag: "55551d9d-0" Expires: Sat, 13 Jun 2015 22:11:45 GMT Cache-Control: max-age=2592000 Accept-Ranges: bytes[root@localhost vhosts]# touch /usr/local/nginx/html/2.js [root@localhost vhosts]# curl -x127.0.0.1:80 www.111.com/2.js -I HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Thu, 14 May 2015 22:11:00 GMT Content-Type: application/javascript Content-Length: 0 Last-Modified: Thu, 14 May 2015 22:10:53 GMT Connection: keep-alive ETag: "55551d6d-0" Expires: Fri, 15 May 2015 10:11:00 GMT Cache-Control: max-age=43200 Accept-Ranges: bytes

五、防盗链

在nginx默认主机default.conf中的server部分中添加如下代码:

 // 对taobao、baidu、google、soso这些域名的网站不进行盗链。如果不是规定的域名,返回403错误;或者跳转到一个自定义的图片上;

    location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ {  

      valid_referers none blocked server_names  *.taobao.com *.baidu.com  *.google.com *.google.cn *.soso.com; 

      if ($invalid_referer) {

          return 403;

          #rewrite ^/ http://www.example.com/nophoto.gif;

       }

     }


~* 代表不区分大小写的匹配;


如同一个配置文件中都有~ 匹配的话,只匹配最上面的;把图片文件的缓存和不记录日志代码,放到一个~匹配中都生效;

    location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ {
         expires 10d;
         valid_referers none blocked server_names *.1.com *.a.com *.b.com *.baidu.com\
         *.google.com *.google.cn *.soso.com ;
         if ($invalid_referer) {
              return 403;
              #rewrite ^/ http://www.example.com/nophoto.gif;
         }
         access_log off;
    }


使用curl -e测试,需要加http://  使用qq.com访问图片显示403错误,使用1.com是200  OK;验证防盗链成功;

[root@localhost vhosts]# curl -x127.0.0.1:80 -e "http://www.qq.com"  192.168.20.30/1.jpg -I HTTP/1.1 403 Forbidden Server: nginx/1.6.2 Date: Fri, 15 May 2015 08:28:07 GMT Content-Type: text/html Content-Length: 168 Connection: keep-alive [ root@localhost vhosts]# curl -x127.0.0.1:80 -e "http://www.1.com"  192.168.20.30/1.jpg -I HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Fri, 15 May 2015 08:28:16 GMT Content-Type: p_w_picpath/jpeg Content-Length: 0 Last-Modified: Fri, 15 May 2015 07:55:55 GMT Connection: keep-alive ETag: "5555a68b-0" Accept-Ranges: bytes


有关nginx配置用户认证、域名跳转、日志记录、静态文件缓存、防盗链的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  9. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  10. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

随机推荐