就此别过

文章 评论 浏览 29

就此别过 2025-02-10 01:40:56

您可以使用 rollingfunctions 映射

julia> a = reshape(1:16, 4, 4)
4×4 reshape(::UnitRange{Int64}, 4, 4) with eltype Int64:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> using RollingFunctions

julia> mapslices(x -> runmean(x, 3), a, dims = 1)
4×4 Matrix{Float64}:
 1.0  5.0   9.0  13.0
 1.5  5.5   9.5  13.5
 2.0  6.0  10.0  14.0
 3.0  7.0  11.0  15.0

You can do this with RollingFunctions and mapslices:

julia> a = reshape(1:16, 4, 4)
4×4 reshape(::UnitRange{Int64}, 4, 4) with eltype Int64:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> using RollingFunctions

julia> mapslices(x -> runmean(x, 3), a, dims = 1)
4×4 Matrix{Float64}:
 1.0  5.0   9.0  13.0
 1.5  5.5   9.5  13.5
 2.0  6.0  10.0  14.0
 3.0  7.0  11.0  15.0

朱莉娅矩阵的列的平均值

就此别过 2025-02-08 20:46:25

您可以使用使用并比较两个表1 x 1的列来实现它。要比较tableone的tablewo,您需要使用加入,在此查询中,我使用左JOIN。

SELECT a.id, a.`uid`, 
IF(a.`thingone`=1, b.`thingone`, NULL) AS thingone,
IF(a.`thingtwo`=1, b.`thingtwo`, NULL) AS thingtwo,
IF(a.`thingthree`=1, b.`thingthree`, NULL) AS thingthree FROM tableone a
LEFT JOIN tabletwo b ON uid=oid;

检查 mysql if()function function 以获取更多详细信息。

You can achieve it by using IF and comparing the columns from both tables 1 by 1. To compare the tabletwo from tableone you need to use JOIN, in this query I use a LEFT JOIN.

SELECT a.id, a.`uid`, 
IF(a.`thingone`=1, b.`thingone`, NULL) AS thingone,
IF(a.`thingtwo`=1, b.`thingtwo`, NULL) AS thingtwo,
IF(a.`thingthree`=1, b.`thingthree`, NULL) AS thingthree FROM tableone a
LEFT JOIN tabletwo b ON uid=oid;

Check MySQL IF() Function for more details.

MySQL如何选择字段等于另一表中的某些东西?

就此别过 2025-02-08 10:02:35

检查这是否与问题12850 /code>在合并请求管道中均为零”。
问题28252 ci_merge_request_target_branch_sha 在分离的合并请求管道中“

尝试一个简单的测试,以查看您当前版本的gitlab:是否可以更好地工作:

image: node:8

test-ci-vars:
  only:
    - master
    - merge_requests
  script:
    - echo CI_COMMIT_REF_NAME=${CI_COMMIT_REF_NAME}
    - echo CI_MERGE_REQUEST_SOURCE_BRANCH_SHA=${CI_MERGE_REQUEST_SOURCE_BRANCH_SHA}
    - echo CI_MERGE_REQUEST_TARGET_BRANCH_SHA=${CI_MERGE_REQUEST_TARGET_BRANCH_SHA}
    - echo CI_MERGE_REQUEST_SOURCE_BRANCH_NAME=${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME}
    - echo CI_MERGE_REQUEST_TARGET_BRANCH_NAME=${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}

Check if this is related to issue 12850 "CI_COMMIT_BEFORE_SHA is all zero in a merge request pipeline".
Or issue 28252 "Expose CI_MERGE_REQUEST_SOURCE_BRANCH_SHA and CI_MERGE_REQUEST_TARGET_BRANCH_SHA in detached merge request pipelines"

Try a simple test to see if that would work better with your current version of GitLab:

image: node:8

test-ci-vars:
  only:
    - master
    - merge_requests
  script:
    - echo CI_COMMIT_REF_NAME=${CI_COMMIT_REF_NAME}
    - echo CI_MERGE_REQUEST_SOURCE_BRANCH_SHA=${CI_MERGE_REQUEST_SOURCE_BRANCH_SHA}
    - echo CI_MERGE_REQUEST_TARGET_BRANCH_SHA=${CI_MERGE_REQUEST_TARGET_BRANCH_SHA}
    - echo CI_MERGE_REQUEST_SOURCE_BRANCH_NAME=${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME}
    - echo CI_MERGE_REQUEST_TARGET_BRANCH_NAME=${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}

Gitlab管道| ci_commit_before_sha在$ ci_pipeline_source ='web的情况下为零。

就此别过 2025-02-08 01:31:12

使用CSV文件时,您应该使用 pandas 图书馆。
但是,如果您想在平原的python中进行行,这是一种解决方案。

with open('containers.txt', 'r') as f:
    with open('output.txt', 'w') as out:
        for line in f:
            if line: #skip empty lines
                data = list(filter(None, map(lambda x: x.strip(), line.split('|')))) #one-liner to split the line in its data-fields and remove empty ones
                if len(data) == 4: #if the Client is missing the len will be 3
                    client = line[:9] #save the Client field
                    out.write(line + '\n')
                else:
                    out.write(f'{client}{line[9:]}\n') #use the saved Client field to fill in the gaps

输出文件现在包含:

|Client | Container weight | Country of Origin | Product code |
|S4378  |     450 Ton      | China             | 457841       |
|S4378  |     350 Ton      | Japan             | 457841       |
|S4378  |     900 Ton      | Japan             | 457841       |
|S4378  |     589 Ton      | China             | 457841       |
|S4978  |    1400 Ton      | Mexico            | 457841       |
|S4978  |     980 Ton      | Emirates          | 457841       |
|S4978  |     550 Ton      | China             | 457841       |
|S4578  |     450 Ton      | China             | 457841       |

When working with csv files, you should be using the pandas library.
However, if you want to do it in plain python, line by line, this is one solution.

with open('containers.txt', 'r') as f:
    with open('output.txt', 'w') as out:
        for line in f:
            if line: #skip empty lines
                data = list(filter(None, map(lambda x: x.strip(), line.split('|')))) #one-liner to split the line in its data-fields and remove empty ones
                if len(data) == 4: #if the Client is missing the len will be 3
                    client = line[:9] #save the Client field
                    out.write(line + '\n')
                else:
                    out.write(f'{client}{line[9:]}\n') #use the saved Client field to fill in the gaps

The output file now contains:

|Client | Container weight | Country of Origin | Product code |
|S4378  |     450 Ton      | China             | 457841       |
|S4378  |     350 Ton      | Japan             | 457841       |
|S4378  |     900 Ton      | Japan             | 457841       |
|S4378  |     589 Ton      | China             | 457841       |
|S4978  |    1400 Ton      | Mexico            | 457841       |
|S4978  |     980 Ton      | Emirates          | 457841       |
|S4978  |     550 Ton      | China             | 457841       |
|S4578  |     450 Ton      | China             | 457841       |

如何从文本文件打印表并填充空空间?

就此别过 2025-02-07 18:40:27

您需要做两件事,以便您可以从浏览器中列出一个容器的内容:

第一:设置SAS以具有两个两个权限:读取列表。如果仅添加读取权限,则无法列出容器的内容。

下一个:将两个附加的Querystring参数附加到您从浏览器中访问的URI:

  • Restype = container
  • comp = list,

因此您最终会得到类似的内容:

https://<acct>.blob.core.windows.net/<container>?restype=container&comp=list&sp=rl&st=2022-05-24T12:16:02Z&se=2022-05-24T20:16:02Z&spr=https&sv=2020-08-04&sr=c&sig=...

You'll need to do two things, so that you can list a container's contents from your browser:

First: Set up your SAS to have two permissions: Read and List. If you only add Read permissions, you can't list the contents of a container.

Next: append two additional querystring parameters to the URI you visit from within your browser:

  • restype=container
  • comp=list

So, you'd end up with something like this:

https://<acct>.blob.core.windows.net/<container>?restype=container&comp=list&sp=rl&st=2022-05-24T12:16:02Z&se=2022-05-24T20:16:02Z&spr=https&sv=2020-08-04&sr=c&sig=...

列出浏览器中的Azure存储斑点内容

就此别过 2025-02-07 16:51:42

当服务器

app \ providers \ appServiceProvider.php 中使用HTTP时,您可以强迫应用程序在服务资产文件中使用HTTPS。

public function boot()
    {
        // Fix https
        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
            $this->app['request']->server->set('HTTPS', true);
        }
    }

You can force app to use https in serving asset files when the server is using https

In App\Providers\AppServiceProvider.php

public function boot()
    {
        // Fix https
        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
            $this->app['request']->server->set('HTTPS', true);
        }
    }

与Ngrok共享Laravel 9导致产生错误的URL

就此别过 2025-02-07 15:59:20

由于 dtype arr 是布尔值,因此当您在该数组中进行分配时,它正在被施放以匹配 dtype 。您需要一个带有适当 dtype 的数组来执行此操作:

arr = arr.astype(np.float64)
arr[row, col] = 5.0

Since the dtype of arr is boolean, when you make assignments within that array, it is being cast to match the dtype. You need an array with the appropriate dtype to do this:

arr = arr.astype(np.float64)
arr[row, col] = 5.0

将选择的整数值分配给true / false值,在0和1以外的其他布尔值中

就此别过 2025-02-07 12:53:46

我认为不需要 ElementHTML
您只需通过搜索CSS选择器来使用 childris_element

...
driver_BV.get("https://www.qvc.com/handbags-and-luggage/handbags/clutches/_/N-1cknw/c.html?qq=mh")
product_BV=[]
price_BV=[]
Final=[]
children_element=driver_BV.find_elements_by_css_selector(".plContent .galleryItem")

它将找到60件商品。
之后,错误一直在发生,我认为您需要在循环中修复这些错误。

I think the elementHTML isn't necessary.
You just use the children_element by searching for css selector.

...
driver_BV.get("https://www.qvc.com/handbags-and-luggage/handbags/clutches/_/N-1cknw/c.html?qq=mh")
product_BV=[]
price_BV=[]
Final=[]
children_element=driver_BV.find_elements_by_css_selector(".plContent .galleryItem")

It will find 60 items of goods.
After that, the error keeps occurring and I think you need to fix those errors in for loop.

从网络检索数据

就此别过 2025-02-06 20:28:20

帐户B中的任何人都可以担任角色

否,那是不起作用的。在帐户B中,任何IAM实体(用户,角色)都希望访问该角色,仍然需要明确的IAM权限来执行此操作。

如果您只希望lambda担任该角色,则必须使用lambda executone角色:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "<arn-of-lambda-exec-role-from-acc-B-to-assume-the-role"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}

anyone in account B can assume the role

No, that's does not work that way. Any IAM entity (user, role) in account B which wants to access that role, still needs explicit IAM permissions to do so.

If you want only the lambda to assume the role, you have to use lambda executone role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "<arn-of-lambda-exec-role-from-acc-B-to-assume-the-role"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}

如何缩小AWS运动跨帐户角色的范围

就此别过 2025-02-06 13:37:07

403意味着您的SAS令牌或共享密钥有问题。您可以使用存储资源管理器以相同的配置生成SAS,并查看其是否有效。

Azure表存储是一种在云中存储非相关结构化数据(也称为结构化NOSQL数据)的服务,它提供了一个 schemaless 设计的密钥/属性存储。没有简单的方法可以查询表格中所有实体的所有属性的结合。

解决方法 - 您可以拿出数据并在工会上做明显的事情。

您可以参考此 link 有关更多信息

403 means there is something wrong with your SAS token or shared key. You can use storage explorer to generate SAS with the same configuration and see if it works.

Azure Table storage is a service that stores non-relational structured data (also known as structured NoSQL data) in the cloud, providing a key/attribute store with a schemaless design. There is no easy way to query the union of all properties of all entities in a table.

Workaround – You can pull out the data and do a distinct on the union.

You can refer this link for more information

如何使用节点从存储帐户表获取特定列?

就此别过 2025-02-05 11:30:38

如果有人遇到相同的问题,答案是neo4j浏览器显示不存在的节点。查询执行正常...

If anyone is having the same problem, the answer is that the Neo4j browser is display nonexistent nodes. The query executes fine…

合并时neo4j创建随机空节点

就此别过 2025-02-05 09:29:16

参考

堆栈溢出具有许多其他重要资源可以入门:

甚至是新手友好的正则概述:

经常使用的占位符

  • 。*匹配任何内容,甚至是一个空字符串。您不想在任何地方使用此模式,但通常是在最后一个后备规则中。
  • [^/]+更经常用于路径段。除了前锋斜线以外,它都与任何东西相匹配。
  • \ d+仅与数字字符串匹配。
  • \ w+匹配字母数字字符。它基本上是 [A-ZA-Z0-9 _] 的速记。
  • [\ w \ - ]+用于“ slug” - 式路径段,使用字母,数字,dash - _ < - _ << /code>
  • [\ w \ - 。,]+添加时间和逗号。喜欢中的Escaped \ - dash […] charclasses。
  • \。表示字面时期。否则 之外[…] 是任何符号的占位符。

这些占位符中的每一个通常都包裹在(…)括号作为捕获组中。整个模式通常在^………$ 开始 +结束标记中。引用“模式”是可选的。

重写

以下示例是以PHP为中心的,更易于增量,更容易适应类似情况。
它们只是摘要,通常链接到更多的变化或详细的Q&amp; AS。

  • 静态映射
    /contact

    将一些页面名称缩短到内部文件方案最简单:

     重写 ^联系人$ templ/contact.html
     重写 ^大约$ $ php
     
  • 数字标识符
    /object/123

    将诸如之类的快捷方式介绍http://example.com/article/531 也很容易。数字占位符只需重新命名 $ _ get 参数:

     重新写入 ^actits/(\ d+)$ actity-show.php?id = $ 1
     #└└└└邮编 - ─-─-─-─-─-─-─-─-─达队 - ─-─达队 - ─-─-─-─- - ┘
     
  • slug式占位符

    /atrect/with some-title-slug

    您可以轻松地扩展该规则以允许/atrate/title-string 占位符:

     重新写入 ^Article/([\ w-]+)$ actity-show.php?title = $ 1
     #└└└└届└└邮编 - ─-─-─达克 - ─达队 - ─达队 - ─..- - ─达队 - ─-─-─-─-─-─-─- - ┘
     

    请注意,您的脚本 必须能够(或适应)将这些标题映射回数据库ID。单独的重写无法从稀薄的空气中创建或猜测信息。

  • 带有数字前缀的slugs
    /readable/123-plus-title

    因此,您经常会看到混合/atrate/529-title-slug 实践中使用的路径:

     重新写入 ^Article/(\ D+) - ([\ w-]+)$ action.php?id = $ 1&amp; title = $ 2
     #└└└└─押期至前 - 达克 - ─-─-─-─-─-─-─-─-─杏仁 - ─-─-─-─-─-─-┘
     

    现在,您可以跳过 title = $ 2 ,因为无论如何您的脚本通常都依靠数据库ID。 -title-slug 已成为任意URL装饰

  • 带有替代列表的统一性
    /foo/… /bar/… <代码>/baz/…

    如果您对多个虚拟页面路径有类似的规则,则可以使用 | 替代列表匹配并将其压缩。然后再次将它们重新分配到内部获取参数:

     ###┌┌届┌┌€ - �I-────-─-─-─-─-─-─-─-─-─-─-─- - ┐
     重写 ^(博客| post |用户)/(\ w+)$ disp.php?type = $ 1&amp; id = $ 2
     #└└└前往# - ─-─达克 - ─达克 - ─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-
     

    您可以将它们分为单个重写是否应该过于复杂。

  • 将相关的URL派遣到不同的后端
    /date/date/switch/backend

    对替代列表的更实际使用是将请求路径映射到不同的脚本。例如,根据日期为较旧的Web应用程序提供统一的URL:

     ###┌┌┌届€─-€───杏仁 - ─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-─-┐
     #│││││┌┌届─-─-─-─-─-─-┼─- - ─-─-─-─-─-─-─-─-─-┐
     重写 ^blog/(2009 | 2010 | 2011)/([\ d-]+)/?$ old/blog.php?date = $ 2
     重写 ^blog/(\ d+)/([\ d-]+)/?$ MODENAL/blog/index.php?start = $ 2
     #└└└前往# -  �—─-─达克 - ─-─-─-─-─达恩至─........................................─..-─..-─杏仁 - ─-─-─-─-─-─-─-┘
     

    这只是将2009-2011的帖子帖子映射到一个脚本,所有其他年都隐含地贴在另一个处理程序上。
    请注意更具体的规则首先。每个脚本可能使用不同的get参数。

  • 其他定界符不仅仅是/路径斜线
    /user-user-duse-123-name

    您通常会看到重写以模拟虚拟目录结构。但是您并没有被迫不创造。您还可以使用 - 连字符进行分割或结构。

     重写 ^用户 - (\ d+)$ show.php?什么=用户&amp; id = $ 1
     #└└└└─-─-─-─-─-─-─-─-─-─-─达队 - ─-─-─-─-─-─-─-─-┘
     #这可以使用`(\ w+)`或者用于用户名而不是ID。
     

    对于也常见的 /wiki:page_name 方案:

     重写 ^Wiki:(\ w+):(\ w+)$ wiki.php?sect = $ 1&amp; page = $ 2 
     #└└前达克 - ─-┼───-─-─-─-─-─-─-──达队 - ─-─-─- - ┘┘
     #└└└└─-─-─-─-─-─-─-─-─-─达队 - ─..-─..- - ─达队 - ─-─-─- - ┘
     

    有时,它适合在/ -delimiters和之间交替:在同一规则中。或者再次有两个重写器将变体映射到不同的脚本。

  • 可选尾声/ slash
    /dir = /dir/dir/

    选择目录风格的路径时,您可以在最终/

    的情况下使其可达到

     重写 ^blog/([\ w-]+)/?$ blog/show.php?id = $ 1
     #┗┛
     

    现在,这两个都可以处理 http://example.com/blog/123 /blog/123/ /?$ 方法很容易附加到任何其他重写。

  • 虚拟路径的灵活片段
    。*/。*/。*/。*

    大多数规则您会遇到映射一个约束的/…/资源路径段到个人获取参数的段。某些脚本处理可变数量的选项
    Apache Regexp引擎不允许将其任意数字选中。但是您可以轻松地将其扩展到规则块中:

     重写 ^(\ w+)/?$ in.php?a = $ 1
     重写 ^(\ w+)/(\ w+)/?$ in.php?a = $ 1&amp; b = $ 2
     重写 ^(\ w+)/(\ w+)/(\ w+)/?$ in.php?a = $ 1&amp; b = $ 2&amp; c = $ 3
     #└└└└届─- - 流行 -   -   -  −流园  -   -   - ──-─-─-─-─-─-─-─-─-─- -   - 流行 - ─-─-─-─-─- - ─-─-┘
     

    如果您最多需要五个路径段,则将此方案复制为五个规则。您当然可以使用更具体的 [^/]+占位符。
    在这里,订购并不重要,没有重叠。因此,首先拥有最常用的路径是可以的。

    另外,您可以通过?p [] = $ 1&amp; p [] = $ 2&amp; p [] = 3 查询字符串 - 如果您的脚本仅优先 - 分裂。
    (尽管只使用ALL规则并让脚本本身将段从请求_uri扩展出来。)

    另请参见:如何将我的URL路径段转换为Query String key-value对?

  • 可选片段

    prefix/opt?/opt?/opt?/code>

    一个常见的变化是在规则中具有可选的前缀。如果您周围有静态字符串或更多受约束的占位符,这通常是有道理的:

     重写 ^(\ w+)(?:/([ ^/]+))?/(\ w+)$?main = $ 1&amp; opt = $ 2&amp; suffix = $ 3
     

    现在,更复杂的模式(?:/([^/])+)?只需包装 nontaps a nontaper (?:…) 组,使其可选)?。包含
    占位符([^/]+)将是替代模式 $ 2 ,但是如果没有中间/…/路径,请空置。

  • 捕获其余的

    /prefix/prefix/123-capture/…/*/…whythy…

    如前所述,您通常不希望过于通用的重写模式。但是,将静态和特定比较与

      rewriterule ^(特定)/prefix/(\ d+)(/.*)?$ speci.php?id = $ 2&amp; eapherparams = $ 2
     

    此可选化任何/…/…/…尾随路径段。当然,这需要处理脚本将它们拆分, variabl-ifie 提取的参数
    这是 web-“ mvc” Frameworks。

  • 尾声“扩展”
    /old/path.html

    URL实际上没有文件扩展名。这就是整个引用的内容(= url是虚拟定位器,不一定是直接文件系统图像)。
    但是,如果您之前有1:1的文件映射,则您的可以更简单的规则:

     重写 ^样式/([\ w \。\  - ]+)\。css $ sass-cache.php?old_fn_base = $ 1
     重写 ^images/([\ w \。\  - ]+)\。gif $ png-converter.php?load_from = $ 2
     

    其他常见用途是重新启动 .html 途径到新的 .php 处理程序,或者仅适用于个人(实际/真实)文件的目录名称。

  • ping-pong(重定向和重写一致)

    /ugly.html ←→ /pretty kbd>

    因此,在某个时候,您正在重写HTML页面以仅带有漂亮的链接,如
    同时,您仍然会收到有关 Old 路径的请求,有时甚至是从书签中获得的。如 vormaround ,您可以平台浏览器以显示/建立
    新的URL。

    这种常见的窍门涉及发送30倍/位置重定向每当传入的URL遵循过时的/丑陋的命名方案时。
    然后,浏览器将 rerequest 新/漂亮的URL,然后将其重写(内部)为原始或新位置。

     #旧/丑陋传入路径的重定向浏览器
     重写 ^旧 /团队\ .html $ /teams [r = 301,QSA,结束]
    
     #内部重新映射已经出现的请求
     重写 ^teams $ teams.php [qsa,end]
     

    请注意此示例如何仅使用 [end] 而不是 [L] 安全地交替。对于较旧的Apache 2.2版本,您可以使用其他解决方法,此外还可以重新映射
    查询字符串参数例如:
    重定向丑陋,回到漂亮的路线,重新回到丑陋的路径,没有无限循环

  • 空格 在模式中

    不是在浏览器地址栏中漂亮,但是您可以在URL中使用空格。对于重写模式,使用Backslash-escaped \␣空格。
    否则只是 - 引用整个模式或替代:

     重写“^此[\ w]+/(。*)$“” index.php?id = $ 1” [l]
     

    客户端将URL与+%20 序列化。然而,在重写中,它们用所有相对路径段的字面字符进行解释。

普遍存在的 .htaccess 陷阱

现在用一粒盐将其带走。并非所有建议都可以推广到所有情况下。
这只是众所周知的简单摘要和一些毫无意义的绊脚石:

  • eNable mod_rewrite .htaccess

    实际使用重写曲线,在每个导向配置文件中必须:

    • 检查您的服务器 allioverride all 启用。否则,您的每个指导 .htaccess 指令将被忽略,并且重新写入将无法正常工作。

    • 显然 mod_rewrite 启用在您的 httpd.conf 模块部分中。


    • 仍然使用上的 rewriteEngine预先预留每个规则列表。虽然mod_rewrite在&lt; virtualHost&gt; and &lt; directory&gt; e节中隐含地活动。
      每个指导 .htaccess 文件需要单独召唤它。


  • 领先的斜杠^/无法匹配

    您不应使用 .htaccess 使用^/正常地重写图案:

     重写 ^/actity/\ d+$…
                  ↑
     

    这在旧教程中经常看到。对于古代Apache 1.x版本,它曾经是正确的。如今,请求路径在 .htaccess 重新写入曲目中方便地完全完全目录相关 。只需将领先的/离开即可。

    ·这就是为什么您经常看到它的^/?用于规则奇偶校验的可选。
    ·或使用 rewriteCond%{request_uri} 您仍然需要匹配领先的/
    ·另请参见 webmaster.se:se:什么时候在mod_rewrite模式中需要领先的斜杠(/)?

  • wrappers begone!

    You've probably seen this in many examples:

    
       改写… 
    
     
    • It does make sense in sections - if it was combined with another fallback option, such as ScriptAliasMatch. (But nobody ever does that).
    • And it's commonly distributed for default .htaccess rulesets with many open source projects. There it's just meant as fallback, and keeps "ugly" URLs work as default.

    However you don't want that usually in your own .htaccess files.

    • Firstly, mod_rewrite does not randomly disengage. (If it did, you'd have bigger problems).
    • Were it really be disabled, your RewriteRules still wouldn't work anyway.
    • It's meant to prevent HTTP 500 errors. What it usually accomplishes is gracing your users with HTTP 404 errors instead. (Not so much more user-friendly if you think about it.)
    • Practically it just suppresses the more useful log entries, or server notification mails. You'd be none the wiser as to why your RewriteRules never work.

    What seems enticing as generalized safeguard, often turns out to be an obstacle in practice.

  • Don't use RewriteBase unless needed

    Many copy+paste examples contain a RewriteBase / directive. Which happens to be the implicit default anyway. So you don't actually need this. It's a workaround for fancy VirtualHost rewriting schemes, and misguessed DOCUMENT_ROOT paths for some shared hosters.

    It makes sense to use with individual web applications in deeper subdirectories. It can shorten RewriteRule patterns in such cases. Generally it's best to prefer relative path specifiers in per-directory rule sets.

    See also How does RewriteBase work in .htaccess

  • Disable MultiViews when virtual paths overlap

    URL rewriting is primarily used for supporting virtual incoming paths. Commonly you just have one dispatcher script (index.php) or a few individual handlers (articles.php, blog.php, wiki.php, …). The latter might clash with similar virtual RewriteRule paths.

    A request for /article/123 for example could map to article.php with a /123 PATH_INFO implicitly. You'd either have to guard your rules then with the commonplace RewriteCond !-f+!-d, and/or disable PATH_INFO support, or perhaps just disable Options -MultiViews.

    Which is not to say you always have to. Content-Negotiation is just an automatism to virtual resources.

  • Ordering is important

    See Everything you ever wanted to know about mod_rewrite
    if you haven't already. Combining multiple RewriteRules often leads to interaction. This isn't something to prevent habitually per [L] flag, but a scheme you'll embrace once versed.
    You can re-re-rewrite virtual paths from one rule to another, until it reaches an actual target handler.

    Still you'd often want to have the most specific rules (fixed string /forum/… patterns, or more restrictive placeholders [^/.]+) in the early rules.
    Generic slurp-all rules (.*) are better left to the later ones. (An exception is a RewriteCond -f/-d guard as primary block.)

  • Stylesheets and images stop working

    When you introduce virtual directory structures /blog/article/123 this impacts relative resource references in HTML (such as ).
    Which can be solved by:

    • Only using server-absolute references href="/old.html" or src="/logo.png"
    • Often simply by adding into your HTML section.
      This implicitly rebinds relative references to what they were before.

    You could alternatively craft further RewriteRules to rebind .css or .png paths to their original locations.
    But that's both unneeded, or incurs extra redirects and hampers caching.

    See also: CSS, JS and images do not display with pretty url

  • RewriteConds just mask one RewriteRule

    A common misinterpetation is that a RewriteCond blocks multiple RewriteRules (because they're visually arranged together):

     RewriteCond %{SERVER_NAME} localhost
     RewriteRule ^secret admin/tools.php
     RewriteRule ^hidden sqladmin.cgi
     

    Which it doesn't per default. You can chain them using the [S=2] flag. Else you'll have to repeat them. While sometimes you can craft an "inverted" primary rule to [END] the rewrite processing early.

  • QUERY_STRING exempt from RewriteRules

    You can't match RewriteRule index.php\?x=y, because mod_rewrite compares just against relative paths per default. You can match them separately however via:

     RewriteCond %{QUERY_STRING} \b(?:param)=([^&]+)(?:&|$)
     RewriteRule ^add/(.+)$ add/%1/$1 # ←──﹪₁──┘
     

    See also How can I match query string variables with mod_rewrite?

  • .htaccess vs.

    If you're using RewriteRules in a per-directory config file, then worrying about regex performance is pointless. Apache retains
    compiled PCRE patterns longer than a PHP process with a common routing framework. For high-traffic sites you should however consider
    moving rulesets into the vhost server configuration, once they've been battle-tested.

    In this case, prefer the optionalized ^/? directory separator prefix. This allows to move RewriteRules freely between PerDir and server
    config files.

  • Whenever something doesn't work

    Fret not.

    • Compare access.log and error.log

      Often you can figure out how a RewriteRule misbehaves just from looking at your error.log and access.log.
      Correlate access times to see which request path originally came in, and which path/file Apache couldn't resolve to (error 404/500).

      This doesn't tell you which RewriteRule is the culprit. But inaccessible final paths like /docroot/21-.itle?index.php may give away where to inspect further.
      Otherwise disable rules until you get some predictable paths.

    • Enable the RewriteLog

      See Apache RewriteLog docs. For debugging you can enable it in the vhost sections:

      # Apache 2.2
      RewriteLogLevel 5
      RewriteLog /tmp/rewrite.log
      
      # Apache 2.4
      LogLevel alert rewrite:trace5
      #ErrorLog /tmp/rewrite.log
       

      That yields a detailed summary of how incoming request paths get modified by each rule:

      [..] applying pattern '^test_.*
      

      Which helps to narrow down overly generic rules and regex mishaps.

      See also:
      · .htaccess not working (mod_rewrite)
      · Tips for debugging .htaccess rewrite rules

    • Before asking your own question

      As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
      by including prior research and attempts (avoid redundant answers), demonstrate basic understanding, and:

      • Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
      • The complete RewriteRule set, but also single out the presumed defective one.
      • Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
      • An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.

      This nets quicker and more exact answers, and makes them more useful to others.

  • Comment your .htaccess

    If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
    it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
    all the more interested in not treating them like magic blackboxes.

  • It's not "SEO"-URLs

    Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.

    None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.

    What "pretty" URLs should conceptionally be used for is making websites user-friendly.

    1. Having readable and obvious resource schemes.
    2. Ensuring URLs are long-lived (AKA permalinks).
    3. Providing discoverability through /common/tree/nesting.

    However don't sacrifice unique requirements for conformism.

Tools

There are various online tools to generate RewriteRules for most GET-parameterish URLs:

Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.

to uri 'index.php' [..] strip per-dir prefix: /srv/www/vhosts/hc-profi/index.php -> index.php [..] applying pattern '^index\.php

Which helps to narrow down overly generic rules and regex mishaps.

See also:
· .htaccess not working (mod_rewrite)
· Tips for debugging .htaccess rewrite rules

  • Before asking your own question

    As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
    by including prior research and attempts (avoid redundant answers), demonstrate basic understanding, and:

    • Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
    • The complete RewriteRule set, but also single out the presumed defective one.
    • Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
    • An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.

    This nets quicker and more exact answers, and makes them more useful to others.

  • Comment your .htaccess

    If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
    it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
    all the more interested in not treating them like magic blackboxes.

  • It's not "SEO"-URLs

    Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.

    None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.

    What "pretty" URLs should conceptionally be used for is making websites user-friendly.

    1. Having readable and obvious resource schemes.
    2. Ensuring URLs are long-lived (AKA permalinks).
    3. Providing discoverability through /common/tree/nesting.

    However don't sacrifice unique requirements for conformism.

  • Tools

    There are various online tools to generate RewriteRules for most GET-parameterish URLs:

    Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.

    to uri 'index.php'

    Which helps to narrow down overly generic rules and regex mishaps.

    See also:
    · .htaccess not working (mod_rewrite)
    · Tips for debugging .htaccess rewrite rules

  • Before asking your own question

    As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
    by including prior research and attempts (avoid redundant answers), demonstrate basic understanding, and:

    • Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
    • The complete RewriteRule set, but also single out the presumed defective one.
    • Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
    • An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.

    This nets quicker and more exact answers, and makes them more useful to others.

  • Comment your .htaccess

    If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
    it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
    all the more interested in not treating them like magic blackboxes.

  • It's not "SEO"-URLs

    Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.

    None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.

    What "pretty" URLs should conceptionally be used for is making websites user-friendly.

    1. Having readable and obvious resource schemes.
    2. Ensuring URLs are long-lived (AKA permalinks).
    3. Providing discoverability through /common/tree/nesting.

    However don't sacrifice unique requirements for conformism.

  • Tools

    There are various online tools to generate RewriteRules for most GET-parameterish URLs:

    Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.

    References

    Stack Overflow has many other great resources to get started:

    And newcomer-friendly regex overviews even:

    Oft-used placeholders

    • .* matches anything, even an empty string. You don't want to use this pattern everywhere, but often in the last fallback rule.
    • [^/]+ is more often used for path segments. It matches anything but the forward slash.
    • \d+ only matches numeric strings.
    • \w+ matches alphanumeric characters. It's basically shorthand for [A-Za-z0-9_].
    • [\w\-]+ for "slug"-style path segments, using letters, numbers, dash - and _
    • [\w\-.,]+ adds periods and commas. Prefer an escaped \- dash in […] charclasses.
    • \. denotes a literal period. Otherwise . outside of […] is placeholder for any symbol.

    Each of these placeholders is usually wrapped in (…) parentheses as capture group. And the whole pattern often in ^………$ start + end markers. Quoting "patterns" is optional.

    RewriteRules

    The following examples are PHP-centric and a bit more incremental, easier to adapt for similar cases.
    They're just summaries, often link to more variations or detailed Q&As.

    • Static mapping
      /contact, /about

      Shortening a few page names to internal file schemes is most simple:

       RewriteRule ^contact$  templ/contact.html
       RewriteRule ^about$    about.php
      
    • Numeric identifiers
      /object/123

      Introducing shortcuts like http://example.com/article/531 to existing PHP scripts is also easy. The numeric placeholder can just be remapped to a $_GET parameter:

       RewriteRule ^article/(\d+)$    article-show.php?id=$1
       #                      └───────────────────────────┘
      
    • Slug-style placeholders
      /article/with-some-title-slug

      You can easily extend that rule to allow for /article/title-string placeholders:

       RewriteRule ^article/([\w-]+)$    article-show.php?title=$1
       #                       └────────────────────────────────┘
      

      Note that your script must be able (or be adapted) to map those titles back to database-ids. RewriteRules alone can't create or guess information out of thin air.

    • Slugs with numeric prefixes
      /readable/123-plus-title

      Therefore you'll often see mixed /article/529-title-slug paths used in practice:

       RewriteRule ^article/(\d+)-([\w-]+)$    article.php?id=$1&title=$2
       #                      └───────────────────────────────┘
      

      Now you could just skip passing the title=$2 anyway, because your script will typically rely on the database-id anyway. The -title-slug has become arbitrary URL decoration.

    • Uniformity with alternative lists
      /foo/… /bar/… /baz/…

      If you have similar rules for multiple virtual page paths, then you can match and compact them with | alternative lists. And again just reassign them to internal GET parameters:

       #                               ┌─────────────────────────┐
       RewriteRule ^(blog|post|user)/(\w+)$  disp.php?type=$1&id=$2
       #               └───────────────────────────────────┘
      

      You can split them out into individual RewriteRules should this get too complex.

    • Dispatching related URLs to different backends
      /date/SWITCH/backend

      A more practical use of alternative lists are mapping request paths to distinct scripts. For example to provide uniform URLs for an older and a newer web application based on dates:

       #                   ┌─────────────────────────────┐
       #                   │                 ┌───────────┼───────────────┐
       RewriteRule ^blog/(2009|2010|2011)/([\d-]+)/?$ old/blog.php?date=$2
       RewriteRule ^blog/(\d+)/([\d-]+)/?$  modern/blog/index.php?start=$2
       #                          └──────────────────────────────────────┘
      

      This simply remaps 2009-2011 posts onto one script, and all other years implicitly to another handler.
      Note the more specific rule coming first. Each script might use different GET params.

    • Other delimiters than just / path slashes
      /user-123-name

      You're most commonly seeing RewriteRules to simulate a virtual directory structure. But you're not forced to be uncreative. You can as well use - hyphens for segmenting or structure.

       RewriteRule ^user-(\d+)$    show.php?what=user&id=$1
       #                   └──────────────────────────────┘
       # This could use `(\w+)` alternatively for user names instead of ids.
      

      For the also common /wiki:section:Page_Name scheme:

       RewriteRule ^wiki:(\w+):(\w+)$  wiki.php?sect=$1&page=$2 
       #                   └─────┼────────────────────┘       │
       #                         └────────────────────────────┘
      

      Occasionally it's suitable to alternate between /-delimiters and : or . in the same rule even. Or have two RewriteRules again to map variants onto different scripts.

    • Optional trailing / slash
      /dir = /dir/

      When opting for directory-style paths, you can make it reachable with and without a final /

       RewriteRule ^blog/([\w-]+)/?$  blog/show.php?id=$1
       #                         ┗┛
      

      Now this handles both http://example.com/blog/123 and /blog/123/. And the /?$ approach is easy to append onto any other RewriteRule.

    • Flexible segments for virtual paths
      .*/.*/.*/.*

      Most rules you'll encounter map a constrained set of /…/ resource path segments to individual GET parameters. Some scripts handle a variable number of options however.
      The Apache regexp engine doesn't allow optionalizing an arbitrary number of them. But you can easily expand it into a rule block yourself:

       Rewriterule ^(\w+)/?$                in.php?a=$1
       Rewriterule ^(\w+)/(\w+)/?$          in.php?a=$1&b=$2
       Rewriterule ^(\w+)/(\w+)/(\w+)/?$    in.php?a=$1&b=$2&c=$3
       #              └─────┴─────┴───────────────────┴────┴────┘
      

      If you need up to five path segments, then copy this scheme along into five rules. You can of course use a more specific [^/]+ placeholder each.
      Here the ordering isn't as important, as neither overlaps. So having the most frequently used paths first is okay.

      Alternatively you can utilize PHPs array parameters via ?p[]=$1&p[]=$2&p[]=3 query string here - if your script merely prefers them pre-split.
      (Though it's more common to just use a catch-all rule, and let the script itself expand the segments out of the REQUEST_URI.)

      See also: How do I transform my URL path segments into query string key-value pairs?

    • Optional segments
      prefix/opt?/.*

      A common variation is to have optional prefixes within a rule. This usually makes sense if you have static strings or more constrained placeholders around:

        RewriteRule ^(\w+)(?:/([^/]+))?/(\w+)$  ?main=$1&opt=$2&suffix=$3
      

      Now the more complex pattern (?:/([^/])+)? there simply wraps a non-capturing (?:…) group, and makes it optional )?. The contained
      placeholder ([^/]+) would be substitution pattern $2, but be empty if there's no middle /…/ path.

    • Capture the remainder
      /prefix/123-capture/…/*/…whatever…

      As said before, you don't often want too generic rewrite patterns. It does however make sense to combine static and specific comparisons with a .* sometimes.

       RewriteRule ^(specific)/prefix/(\d+)(/.*)?$  speci.php?id=$2&otherparams=$2
      

      This optionalized any /…/…/… trailing path segments. Which then of course requires the handling script to split them up, and variabl-ify extracted parameters
      itself (which is what Web-"MVC" frameworks do).

    • Trailing file "extensions"
      /old/path.HTML

      URLs don't really have file extensions. Which is what this entire reference is about (= URLs are virtual locators, not necessarily a direct filesystem image).
      However if you had a 1:1 file mapping before, you can craft simpler rules:

       RewriteRule  ^styles/([\w\.\-]+)\.css$  sass-cache.php?old_fn_base=$1
       RewriteRule  ^images/([\w\.\-]+)\.gif$  png-converter.php?load_from=$2
      

      Other common uses are remapping obsolete .html paths to newer .php handlers, or just aliasing directory names only for individual (actual/real) files.

    • Ping-Pong (redirects and rewrites in unison)
      /ugly.html ←→ /pretty

      So at some point you're rewriting your HTML pages to carry only pretty links, as outlined by deceze.
      Meanwhile you'll still receive requests for the old paths, sometimes even from bookmarks. As workaround, you can ping-pong browsers to display/establish
      the new URLs.

      This common trick involves sending a 30x/Location redirect whenever an incoming URL follows the obsolete/ugly naming scheme.
      Browsers will then rerequest the new/pretty URL, which afterwards is rewritten (just internally) to the original or new location.

       # redirect browser for old/ugly incoming paths
       RewriteRule ^old/teams\.html$ /teams [R=301,QSA,END]
      
       # internally remap already-pretty incoming request
       RewriteRule ^teams$ teams.php        [QSA,END]
      

      Note how this example just uses [END] instead of [L] to safely alternate. For older Apache 2.2 versions you can use other workarounds, besides also remapping
      query string parameters for example:
      Redirect ugly to pretty URL, remap back to the ugly path, without infinite loops

    • Spaces in patterns
      /this+that+

      It's not that pretty in browser address bars, but you can use spaces in URLs. For rewrite patterns use backslash-escaped \␣ spaces.
      Else just "-quote the whole pattern or substitution:

       RewriteRule  "^this [\w ]+/(.*)$"  "index.php?id=$1"  [L]
      

      Clients serialize URLs with + or %20 for spaces. Yet in RewriteRules they're interpreted with literal characters for all relative path segments.

    Frequent duplicates:

    Prevalent .htaccess pitfalls

    Now take this with a grain of salt. Not every advise can be generalized to all contexts.
    This is just a simple summary of well-known and a few unobvious stumbling blocks:

    • Enable mod_rewrite and .htaccess

      To actually use RewriteRules in per-directory configuration files you must:

      • Check that your server has AllowOverride All enabled. Otherwise your per-directory .htaccess directives will go ignored, and RewriteRules won't work.

      • Obviously have mod_rewrite enabled in your httpd.conf modules section.

      • Prepend each list of rules with RewriteEngine On still. While mod_rewrite is implicitly active in <VirtualHost> and <Directory> sections,
        the per-directory .htaccess files need it individually summoned.

    • The leading slash ^/ won't match

      You shouldn't start your .htaccess RewriteRule patterns with ^/ normally:

       RewriteRule ^/article/\d+$  …
                    ↑
      

      This is often seen in old tutorials. And it used to be correct for ancient Apache 1.x versions. Nowadays request paths are conveniently fully directory-relative in .htaccess RewriteRules. Just leave the leading / out.

      · Note that the leading slash is still correct in <VirtualHost> sections though. Which is why you often see it ^/? optionalized for rule parity.
      · Or when using a RewriteCond %{REQUEST_URI} you'd still match for a leading /.
      · See also Webmaster.SE: When is the leading slash (/) needed in mod_rewrite patterns?

    • <IfModule *> wrappers begone!

      You've probably seen this in many examples:

      <IfModule mod_rewrite.c>
         Rewrite… 
      </IfModule>
      
      • It does make sense in <VirtualHost> sections - if it was combined with another fallback option, such as ScriptAliasMatch. (But nobody ever does that).
      • And it's commonly distributed for default .htaccess rulesets with many open source projects. There it's just meant as fallback, and keeps "ugly" URLs work as default.

      However you don't want that usually in your own .htaccess files.

      • Firstly, mod_rewrite does not randomly disengage. (If it did, you'd have bigger problems).
      • Were it really be disabled, your RewriteRules still wouldn't work anyway.
      • It's meant to prevent HTTP 500 errors. What it usually accomplishes is gracing your users with HTTP 404 errors instead. (Not so much more user-friendly if you think about it.)
      • Practically it just suppresses the more useful log entries, or server notification mails. You'd be none the wiser as to why your RewriteRules never work.

      What seems enticing as generalized safeguard, often turns out to be an obstacle in practice.

    • Don't use RewriteBase unless needed

      Many copy+paste examples contain a RewriteBase / directive. Which happens to be the implicit default anyway. So you don't actually need this. It's a workaround for fancy VirtualHost rewriting schemes, and misguessed DOCUMENT_ROOT paths for some shared hosters.

      It makes sense to use with individual web applications in deeper subdirectories. It can shorten RewriteRule patterns in such cases. Generally it's best to prefer relative path specifiers in per-directory rule sets.

      See also How does RewriteBase work in .htaccess

    • Disable MultiViews when virtual paths overlap

      URL rewriting is primarily used for supporting virtual incoming paths. Commonly you just have one dispatcher script (index.php) or a few individual handlers (articles.php, blog.php, wiki.php, …). The latter might clash with similar virtual RewriteRule paths.

      A request for /article/123 for example could map to article.php with a /123 PATH_INFO implicitly. You'd either have to guard your rules then with the commonplace RewriteCond !-f+!-d, and/or disable PATH_INFO support, or perhaps just disable Options -MultiViews.

      Which is not to say you always have to. Content-Negotiation is just an automatism to virtual resources.

    • Ordering is important

      See Everything you ever wanted to know about mod_rewrite
      if you haven't already. Combining multiple RewriteRules often leads to interaction. This isn't something to prevent habitually per [L] flag, but a scheme you'll embrace once versed.
      You can re-re-rewrite virtual paths from one rule to another, until it reaches an actual target handler.

      Still you'd often want to have the most specific rules (fixed string /forum/… patterns, or more restrictive placeholders [^/.]+) in the early rules.
      Generic slurp-all rules (.*) are better left to the later ones. (An exception is a RewriteCond -f/-d guard as primary block.)

    • Stylesheets and images stop working

      When you introduce virtual directory structures /blog/article/123 this impacts relative resource references in HTML (such as <img src=mouse.png>).
      Which can be solved by:

      • Only using server-absolute references href="/old.html" or src="/logo.png"
      • Often simply by adding <base href="/index"> into your HTML <head> section.
        This implicitly rebinds relative references to what they were before.

      You could alternatively craft further RewriteRules to rebind .css or .png paths to their original locations.
      But that's both unneeded, or incurs extra redirects and hampers caching.

      See also: CSS, JS and images do not display with pretty url

    • RewriteConds just mask one RewriteRule

      A common misinterpetation is that a RewriteCond blocks multiple RewriteRules (because they're visually arranged together):

       RewriteCond %{SERVER_NAME} localhost
       RewriteRule ^secret  admin/tools.php
       RewriteRule ^hidden  sqladmin.cgi
      

      Which it doesn't per default. You can chain them using the [S=2] flag. Else you'll have to repeat them. While sometimes you can craft an "inverted" primary rule to [END] the rewrite processing early.

    • QUERY_STRING exempt from RewriteRules

      You can't match RewriteRule index.php\?x=y, because mod_rewrite compares just against relative paths per default. You can match them separately however via:

       RewriteCond %{QUERY_STRING} \b(?:param)=([^&]+)(?:&|$)
       RewriteRule ^add/(.+)$  add/%1/$1  # ←──﹪₁──┘
      

      See also How can I match query string variables with mod_rewrite?

    • .htaccess vs. <VirtualHost>

      If you're using RewriteRules in a per-directory config file, then worrying about regex performance is pointless. Apache retains
      compiled PCRE patterns longer than a PHP process with a common routing framework. For high-traffic sites you should however consider
      moving rulesets into the vhost server configuration, once they've been battle-tested.

      In this case, prefer the optionalized ^/? directory separator prefix. This allows to move RewriteRules freely between PerDir and server
      config files.

    • Whenever something doesn't work

      Fret not.

      • Compare access.log and error.log

        Often you can figure out how a RewriteRule misbehaves just from looking at your error.log and access.log.
        Correlate access times to see which request path originally came in, and which path/file Apache couldn't resolve to (error 404/500).

        This doesn't tell you which RewriteRule is the culprit. But inaccessible final paths like /docroot/21-.itle?index.php may give away where to inspect further.
        Otherwise disable rules until you get some predictable paths.

      • Enable the RewriteLog

        See Apache RewriteLog docs. For debugging you can enable it in the vhost sections:

        # Apache 2.2
        RewriteLogLevel 5
        RewriteLog /tmp/rewrite.log
        
        # Apache 2.4
        LogLevel alert rewrite:trace5
        #ErrorLog /tmp/rewrite.log
        

        That yields a detailed summary of how incoming request paths get modified by each rule:

        [..] applying pattern '^test_.*
        

        Which helps to narrow down overly generic rules and regex mishaps.

        See also:
        · .htaccess not working (mod_rewrite)
        · Tips for debugging .htaccess rewrite rules

      • Before asking your own question

        As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
        by including prior research and attempts (avoid redundant answers), demonstrate basic understanding, and:

        • Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
        • The complete RewriteRule set, but also single out the presumed defective one.
        • Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
        • An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.

        This nets quicker and more exact answers, and makes them more useful to others.

    • Comment your .htaccess

      If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
      it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
      all the more interested in not treating them like magic blackboxes.

    • It's not "SEO"-URLs

      Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.

      None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.

      What "pretty" URLs should conceptionally be used for is making websites user-friendly.

      1. Having readable and obvious resource schemes.
      2. Ensuring URLs are long-lived (AKA permalinks).
      3. Providing discoverability through /common/tree/nesting.

      However don't sacrifice unique requirements for conformism.

    Tools

    There are various online tools to generate RewriteRules for most GET-parameterish URLs:

    Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.

    to uri 'index.php' [..] strip per-dir prefix: /srv/www/vhosts/hc-profi/index.php -> index.php [..] applying pattern '^index\.php

    Which helps to narrow down overly generic rules and regex mishaps.

    See also:
    · .htaccess not working (mod_rewrite)
    · Tips for debugging .htaccess rewrite rules

  • Before asking your own question

    As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
    by including prior research and attempts (avoid redundant answers), demonstrate basic understanding, and:

    • Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
    • The complete RewriteRule set, but also single out the presumed defective one.
    • Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
    • An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.

    This nets quicker and more exact answers, and makes them more useful to others.

  • Comment your .htaccess

    If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
    it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
    all the more interested in not treating them like magic blackboxes.

  • It's not "SEO"-URLs

    Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.

    None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.

    What "pretty" URLs should conceptionally be used for is making websites user-friendly.

    1. Having readable and obvious resource schemes.
    2. Ensuring URLs are long-lived (AKA permalinks).
    3. Providing discoverability through /common/tree/nesting.

    However don't sacrifice unique requirements for conformism.

  • Tools

    There are various online tools to generate RewriteRules for most GET-parameterish URLs:

    Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.

    to uri 'index.php'

    Which helps to narrow down overly generic rules and regex mishaps.

    See also:
    · .htaccess not working (mod_rewrite)
    · Tips for debugging .htaccess rewrite rules

  • Before asking your own question

    As you might know, Stack Overflow is very suitable for asking questions on mod_rewrite. Make them on-topic
    by including prior research and attempts (avoid redundant answers), demonstrate basic understanding, and:

    • Include full examples of input URLs, falsly rewritten target paths, your real directory structure.
    • The complete RewriteRule set, but also single out the presumed defective one.
    • Apache and PHP versions, OS type, filesystem, DOCUMENT_ROOT, and PHPs $_SERVER environment if it's about a parameter mismatch.
    • An excerpt from your access.log and error.log to verify what the existing rules resolved to. Better yet, a rewrite.log summary.

    This nets quicker and more exact answers, and makes them more useful to others.

  • Comment your .htaccess

    If you copy examples from somewhere, take care to include a # comment and origin link. While it's merely bad manners to omit attribution,
    it often really hurts maintenance later. Document any code or tutorial source. In particular while unversed you should be
    all the more interested in not treating them like magic blackboxes.

  • It's not "SEO"-URLs

    Disclaimer: Just a pet peeve. You often hear pretty URL rewriting schemes referred to as "SEO" links or something. While this is useful for googling examples, it's a dated misnomer.

    None of the modern search engines are really disturbed by .html and .php in path segments, or ?id=123 query strings for that matter. Search engines of old, such as AltaVista, did avoid crawling websites with potentially ambigious access paths. Modern crawlers are often even craving for deep web resources.

    What "pretty" URLs should conceptionally be used for is making websites user-friendly.

    1. Having readable and obvious resource schemes.
    2. Ensuring URLs are long-lived (AKA permalinks).
    3. Providing discoverability through /common/tree/nesting.

    However don't sacrifice unique requirements for conformism.

  • Tools

    There are various online tools to generate RewriteRules for most GET-parameterish URLs:

    Mostly just output [^/]+ generic placeholders, but likely suffices for trivial sites.

    参考:mod_rewrite,URL重写和“漂亮链接”解释了

    就此别过 2025-02-05 03:28:40

    截至目前,您的行变量是类型char。这意味着它具有一个字符。如果要存储一个字符串,则可以使用固定大小的字符数组(C风格的字符串)或字符串对象。在C ++字符串对象中,应优选,因为它们比C风格的字符串具有多种优势,包括更高的安全性和较高的使用易用性。

    例如,如果要获取用户输入的字符串对象的长度,则可以写出这样的内容,

    #include <iostream>
    #include <string>
    
    // if you don’t want to use std:: put using namespace std; after the includes
    int main(){
        std::string str;
        int strLength
    
        std::cout << “Enter a Single Word: “;
        std::cin >> str;
    
        strLength = str.lenght();
    
        std::cout << “The length of the word is “ << strLength << std::endl;
    
        return 0;
    }
    

    如果您想获得完整的文本行,

    std::cout << “Enter a Single Word: “;
    std::cin >> str;
    

    替换

    std::cout << “Enter a Line of text: “;
    std::getline(cin, str);
    

    则可以使用C-Style String和strlen ( )但是,安全执行此操作要困难得多,并且通过执行诸如编写字符串之类的事情比所使用的固定大小数组的大小更长,这将使引起问题更容易引起问题,这可能会引起问题,因为可以将额外的数据写入区域不应写入,因此,如果您只是启动,则可能应该使用字符串对象。

    如果您想要有关STD :: String的更多信息,请转到
    https://en.cppreference.com/w/cpp/cpp/string/basic_string/basic_string

    关于strlen为什么要返回40。strlen()工作的方式是,它采用一个称为指针的变量,该变量指向一系列字符的开始,并从指针开始浏览一系列字符,并寻找一个特殊的字符称为null字符'\ 0',并在此空字符之前返回数组中的字符数。如果C风格的字符串不以空字符结束,这可能会导致问题。

    在您提供的代码的情况下,String2包含“”末尾的“”和null字符的所有40个字符,因此,当使用String2调用strlen()时,它会在NULL字符之前计数40个字符。

    在String1的情况下,创建它时,它的大小与非初始化变量线中包含的值相等,在这种情况下似乎是0。这会导致String1用大小为0(根据对于语言标准来说,这是不确定的行为,但在某些情况下可能仍然“工作”)。因为String2后来在存储器中的字符串1之后直接在位置中创建,所以当String1 1时创建的字符串1启动的指针将其传递到Strlen指向string2的启动中,从而导致strlen在String1上调用时有效地测量String2的长度。

    最后,作为小费。尽量避免将变量放置在全局范围(功能之外或其他封装实体之外)。这些全局变量有可能因可能导致代码中问题的方式而无意中改变的风险。通常,最好将这些变量放在主中,然后将它们传递到要使用它们的功能。如果要具有函数影响这些变量,则可以将它们作为引用传递到函数中。为此,您将放置AN&amp;在函数的参数类型的背后,将变量将传递给AS。

    void function(std::string &str);
    
    //… some other code
    
    //… somewhere in main or another function
    
    function(alteredString);
    
    // some other code …
    

    As of now, your line variable is of type char. This means that it holds a single character. If you want to store a string, you can either use a fixed size array of characters (a c-style string) or a string object. In c++ string objects should be preferred as they offer a wide array of advantages over c-style strings including greater security and superior ease of use.

    If you wanted to get the length of a user inputed string object for example, you could write something like this

    #include <iostream>
    #include <string>
    
    // if you don’t want to use std:: put using namespace std; after the includes
    int main(){
        std::string str;
        int strLength
    
        std::cout << “Enter a Single Word: “;
        std::cin >> str;
    
        strLength = str.lenght();
    
        std::cout << “The length of the word is “ << strLength << std::endl;
    
        return 0;
    }
    

    If you want to get a full line of text instead, you would replace

    std::cout << “Enter a Single Word: “;
    std::cin >> str;
    

    With

    std::cout << “Enter a Line of text: “;
    std::getline(cin, str);
    

    You could also use a c-style string and strlen() however, it is far more difficult to do this securely and it will make it easier to cause issues by doing something like writing a string longer than the size of the fixed size array used which can cause issues as the extra data can be written to areas it should not be written to, so if your just starting out you should probably use string objects.

    If you want more information on std::string, go to
    https://en.cppreference.com/w/cpp/string/basic_string

    On why strlen is returning 40. The way strlen() works is it takes a variable called a pointer that points to the start of an array of characters and goes through an array of characters starting at the pointer and looks for a special character called the null character ‘\0’ and returns the number of characters in the array before this null character. This can cause problems if a c-style string does not end in a null character.

    In the case of the code you provided, string2 contains all 40 characters inside of the “” plus the null character at the end, so when strlen() is called using string2, it counts the 40 characters before the null character.

    In the case of string1, when it is created, it is created with the size equal to the value contained in the uninitialized variable line, which in this case appears to be 0. This causes string1 to be created with a size of 0 (according to the language standard this is undefined behavior but it may still “work” in some cases). Because string2 is later created in a position directly after string1 in memory, the pointer to the start of string1 created when string1 is passed into strlen points to the start of string2 causing strlen to effectively measure the length of string2 when called on string1.

    Finally, as a tip. Try to avoid placing variables in the global scope (outside of functions or other encapsulating entities like classes). These global variables are at risk of being unintentionally altered by functions in ways that might cause problems in your code. It is generally better to place these variables in main and pass them to the functions you want to use them in. If you want to have the function affect these variables, you can pass them into the function as references. To do this you would place an & behind the type of the parameter of the function the variable will be passed in as, like this.

    void function(std::string &str);
    
    //… some other code
    
    //… somewhere in main or another function
    
    function(alteredString);
    
    // some other code …
    

    strlen默认为40;?

    就此别过 2025-02-05 02:38:43

    没有可移植的方法可以从Java控制台中读取原始字符。

    上面已经介绍了一些依赖平台的解决方法。但是要真正便携,您必须放弃控制台模式并使用窗口模式,例如AWT或摇摆。

    There is no portable way to read raw characters from a Java console.

    Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.

    如何读取Java中的控制台(用户键入它)的单个字符?

    就此别过 2025-02-05 00:21:45

    在快速视图中,您将数据定义为包含包含三个元素的元组的元组。

    作为解决方案的第一步,应该使用列表,而不是元组元组:

    data = [1, "john", 1/5/2022]
    

    您可以尝试一下,让我知道它是否解决了还是需要更多帮助。

    表示“感谢”是值得赞赏的,但没有回答这个问题。相反,投票最有助于您的答案!如果这些答案对您有帮助,请考虑以更具建设性的方式表示感谢 - 通过对同龄人在这里提出的问题做出自己的答案。

    In a quick view, you defined data as a tuple that contains a tuple with three elements.

    As a first step to solve should use a list instead a tuple of tuples:

    data = [1, "john", 1/5/2022]
    

    Could you try this and let me know if it solves or you need more help.

    Saying “thanks” is appreciated, but it doesn’t answer the question. Instead, vote up the answers that helped you the most! If these answers were helpful to you, please consider saying thank you in a more constructive way – by contributing your own answers to questions your peers have asked here.

    在OpenPyXl Python打开工作簿后,如何打开文本文件

    更多

    推荐作者

    櫻之舞

    文章 0 评论 0

    弥枳

    文章 0 评论 0

    m2429

    文章 0 评论 0

    野却迷人

    文章 0 评论 0

    我怀念的。

    文章 0 评论 0

    更多

    友情链接

      我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
      原文